I want to make a program which prints the following series: 1, -4, 7, -10.......40.
Here's what I wrote up: It doesnt seem to work!! Please help!
#include %26lt;iostream.h%26gt;
int main()
{
double sgn;
for (int i = 1; i %26lt;= 40; i+=3)
{
i = i * sgn;
sgn = sgn * -1;
cout %26lt;%26lt; i %26lt;%26lt; endl;
}
system("PAUSE");
return 0;
}
C++ code, please?
You're not supposed to change the loop variable (i, in this case) inside the loop, and you should initialize sgn. Try this --I didn't test it, but tried to optimize is somewhat:
#include %26lt;iostream.h%26gt;
int main()
{
int sgn = 1;
for (int i = 1; i %26lt;= 40; i+=3)
{
cout %26lt;%26lt; i * sgn; %26lt;%26lt; endl;
sgn = -sgn;
}
system("PAUSE");
return 0;
}
Reply:"sgn" needs to be initialized before you use it ("sgn = 1;"). Also, when you multiply "i", your iterator, by "sgn", your sign, you are changing the length of the outer for loop and its operation drastically. Use a different variable to store the current series value separate from your iterator value (which should not be multiplied by -1).
Try this:
#include %26lt;iostream.h%26gt;
int main()
{
double sgn = -1;
for (int i = 1; i %26lt;= 40; i+=3)
{
sgn = sgn * -1;
cout %26lt;%26lt; (i * sgn) %26lt;%26lt; endl;
}
system("PAUSE");
return 0;
}
Reply:First off, yeah, don't change variable i. That is used for your loop and changing it inside the loop is a bad idea. Unless you need to for loop length but you don't.
Your sgn variable should be initialized before you use it definately. Give it a value before you begin using it that is:
sgn = 0;
You should have a way to know whether the variable should be outputed as a negative number or a positive number. One way is to use a boolean variable which is what I use the variable "isNegative" for. Now only when the negative number should be changed, it is. Your code as it is right now had you not been messing with the counter variable in your loop would have outputed every number as a negative number.
This will be better for you.
#include %26lt;iostream.h%26gt;
int main()
{
double sgn = 0; //initialize variable for later use
bool isNegative = false; //boolean variable to check negative
for (int i = 1; i %26lt;= 40; i+=3)
{
sgn = i;
if(isNegative)
{
sgn = -sgn; //if it's supposed to be negative, negativize it.
isNegative = false; //change variable for next number
}
else //number is already positive no need to change
isNegative = true; //change variable for next number
cout%26lt;%26lt;sgn%26lt;%26lt;endl; //output results
}
system("PAUSE");
return 0;
}
Hope that helps.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment