Question:
C++ Programming HELP?
ALEC
2012-10-07 09:00:40 UTC
Write a complete program that repeatedly reads nonnegative floating point numbers from the console and outputs their square roots. When any negative number is read, the program will terminate with the output "Bye!". Each square root should be printed on a separate line and formatted with two digits precision after the decimal point. (Use the iomanip library.) Do not prompt the user for input or produce any output besides what is specified above.

In order to receive credit, you must use a do-while loop to process the input.

I got the correct output, but I keep getting the "nan" error message and I need help fixing this.
Here is my solution:

#include
#include
#include
using namespace std;

int main()
{
double x;
double y = 0;
do
{
cin >> x;
if (x < 0)
{
cout << "Bye!" << endl;
}
y = sqrt(x);
cout << setprecision(2) << fixed << y << endl;
}
while(x > 0);
return 0;
}
Three answers:
husoski
2012-10-07 09:13:03 UTC
I wonder what you left out, because a while loop seems better than do-while. Oh well, for the credit, one way to fix this is to put the rest of the loop (after the if (x<0) test) into an else block that only executes if the x<0 test fails. That way you won't be taking sqrt(x) when x is negative:



if (x < 0)

{

cout ...

}

else

{

y = sqrt(x);

...

}

} while (x >0);



Also, check your if condition and the while condition at the end. If you don't want to stop after taking the square root of 0, then change to while (x >= 0). If you don't want to take the square root of 0 at all, then change to if (x <= 0) instead.
Arun
2012-10-07 09:50:34 UTC
Try this code its working.....:D

#include

#include

#include



int main()

{

double x;

double y = 0;

do

{

cin >> x;

if (x < 0)

{

cout << "Bye!" << endl;

}

y = sqrt(x);

cout << setprecision(2) << y << endl;

}

while(x > 0);

return 0;

}
ragsdalesr
2017-02-23 15:46:43 UTC
not anymore, at one time C++ grow to be only an extension of C. in view that then, C has replaced, and so has C++. even nonetheless that being pronounced it is common for the same application to collect the two C and C++. the tactic is the same, yet there are in straight forward terms some ameliorations int he libraries which you quite choose the compiler to hyperlink to.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...