Is there anything I can improve on, or any critiques regarding my code or simply a note that may help me in the future?
I know I used a goto but in the scenario it was efficient.
Here is my code . . .
#include <iostream>
#include <conio.h>
#include <windows.h>
#include <cstdlib>
#include <iomanip>
#include <ctime>
using namespace std;
long double dUserInput = 0, dTop = 0, dBottom = 0, dDivider = 0;
int pause()
{
cout << "Paused.\n\nYou pressed a key.\nWould you like to exit this program?" << endl;
while(true)
{
cin.sync();
cout << "(\"YES\"/\"NO\")" << endl;
string sExitOrNot;
cin >> sExitOrNot;
// If entry is "yes", exit after returning 0
if(sExitOrNot == "Yes" ||
sExitOrNot == "yes" ||
sExitOrNot == "YES" ||
sExitOrNot == "yES") exit(0);
// If entry is "no", end execution of this function
else if(sExitOrNot == "No" ||
sExitOrNot == "no" ||
sExitOrNot == "nO" ||
sExitOrNot == "NO")
{
system("CLS");
return 0;
}
// Unrecognised response
else cout << "\"" << sExitOrNot << "\" is unrecognised as a response." << endl;
}
}
void finale(int dUserInput,int dAnswer)
{
cout << "The cube-root of " << dUserInput << " is " << dAnswer << endl;
system("PAUSE");
// Return to main where it (main) will return 0
return;
}
int main()
{
start:
clock();
cout << "Enter a real positive whole number of which\nyou would like to find the cube-root of." << endl;
cin >> dUserInput;
if(dUserInput*dUserInput*dUserInput == dUserInput)
{
finale(dUserInput, dUserInput);
return 0;
}
// Value of top
dTop = dUserInput;
// Value of mid
dDivider = dUserInput/2;
// Value of bottom
dBottom = 0;
cout.precision(16);
system("CLS");
do
{
cout << "Calculating . . .\n\nPress any key to pause.\n\nComparing " << dDivider << " cubed with " << dUserInput << endl;
system("CLS");
if(_kbhit()) pause();
// If the loop has been running for a sufficient time, break
if(clock() >= 100000 || dTop-dBottom <= 0.000000000000001) break;
// If the cube-root was found . . .
if(dDivider*dDivider*dDivider == dUserInput)
{
finale(dUserInput, dDivider);
return 0;
}
// If the midpoint of top and bottom cubed is too high . . .
if(dDivider*dDivider*dDivider > dUserInput){
dTop = dDivider;
dDivider = (dBottom+dDivider)/2; }
// If the midpoint of top and bottom cubed is too low . . .
if(dDivider*dDivider*dDivider < dUserInput){
dBottom = dDivider;
dDivider = (dTop+dDivider)/2;
}
}
while(true);
long double plusOff = dUserInput*1.08, minusOff = dUserInput * 0.92;
// If the cube-root is too far off to be realistic (can happen with clock), goto start
if(!(dDivider*dDivider*dDivider >= minusOff && dDivider*dDivider*dDivider <= plusOff))
{
cout << "There was an error.\n\nPress enter to try again." << endl;
cin.sync();
cin.get();
goto start;
}
cout << "The program could not calculate the exact cube-root of " << dUserInput;
cout << "\n\nEstimate: " << dDivider << "\n\nPress enter to end this program . . ." << endl;
cin.sync();
cin.get();
return 0;
}

New Topic/Question
Reply




MultiQuote






|