Hello, I need to do some exercises, in which I need to use IF in FOR, and im really having trouble with it. The result I need to get in exercises :
1st exercise : if y1=y4, it has to say "Crosses", otherwise "***". In 2nd one, if y>0, it has to say "***".
What I have wrote in 1st and 2nd exercise, but no idea on how to use if to get the correct answers on y. Here is what I have wrote without if, and the results I need to get:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
#include <iostream>
#include <iomanip>
#include <cmath>
usingnamespace std;
int main()
{
double x,y;
for (x=15;x<=25;x++)
{
y=sqrt(x*x+3*x-500);
cout << x << " " << setprecision(3) << y << endl;
}
return 0;
}
What I need to get:
x y
15 ***
16 ***
17 ***
18 ***
19 ***
20 ***
21 2.00
22 7.07
23 9.90
24 12.17
25 14.14
So for your first problem you are getting an error for y. The reason that is happening is because you are trying to take the square root of a negative number. Try using an if statement to display *** if (x*x+3*x-500) < 0.
Thank you for your help. I didnt think its that complicated with all those setw and left. And I have one question about 1st exercise. When I get y, why if(y<0) doesnt work ? I know its square root, but no idea why it doesnt work.
Unless you are working in the complex plane, the square root of -ve numbers does not exist.
The inverse of the square root is a squared number which is always positive.
If a= sqrt(x) then x = a*a and if a is -ve or +ve x will always be +ve because +ve * +ve is +ve, and -ve * -ve is +ve.
So there is no way to get a -ve for x unless complex/imaginary i is allowed, which it isn't. :)