okay this is pretty simple. I have this program thats supposed to add a number to all of its precedents. so if the input was 5, it would add 5+4+3+2+1 and give 15. I know i can implement this in a billion different way and it wouldnt be much of a challenge, but im really confused as to why this isnt working. It gives a large negative number when i run it. thanks.
#include <iostream>
usingnamespace std;
int main()
{
int b;
cout<<"Enter a number, ill return that number plus every number below it: ";
cin>>b;
for (int i=1;i<b;i++)
{
b+=i;
}
cout<<"Number is: "<<b<<endl;
}
#include <iostream>
usingnamespace std;
int main()
{
int b = 0;
cout<<"Enter a number, ill return that number plus every number below it: ";
cin >> b;
int answer = b;
for( int i = 1; i < b; ++ i ){
answer += i;
}
cout<<"Number is: "<<answer<<endl;
return 0;
}
this probably show you what's wrong with your loop condition better.
#include <iostream>
int main()
{
std::cout << "Enter a number, I'll return that number plus every number below it: ";
int b;
std::cin >> b;
std::cout << "You entered: " << b << std::endl;
int answer = 0;
for (int i = b; i != 0; i--)
{
answer += i;
}
std::cout << "Number is: " << answer << std::endl;
return 0;
}
but I've tested it and it isn't wrong
perhaps you miss read it
I am trying to code it as similar as possible to the original
Sure I am adding it in a quite a strange way but it's correct
if the input is 5
5 + 1 + 2 + 3 + 4
I might miss interpret @BHX Specter words ,,
which code are you refering to
and why do you need to post your version of the code if there is nothing wrong with mine...
You are getting overflow (negative answer) because of how you are comparing i to b, but you are constantly updating b in your loop so first time through i is 1 and b is 6 so second iteration through loop it becomes 2 < 6 rather than 2 < 5 like you intended.
@rmxhaha
It was just a general comment on a rather common pitfall of using answer += i; especially if you accidentally do i <= b; I just was in a hurry and didn't elaborate as much as I should have to make my point clear. Was just pointing out that you have to be careful in some situations because you could get an error due to it being the equivalent of
5 + 5 + 4 + 3 + 2 + 1.
rmxhaha wrote:
why do you need to post your version of the code if there is nothing wrong with mine...
With almost 200 posts, I would have figured you would be used to that by now. Everyone has different coding styles and you will find that users will usually post their code of the same problem to show the different methods even after a perfectly functional example was posted.
All you need to trouble shoot a problem like this is put a cout statement in your loop for testing to see what the numbers are that are being calculated.