Home > Back-end >  Sum the result error is the compiler issues?
Sum the result error is the compiler issues?

Time:09-15

#include
using namespace std;

Int main ()
{int sum;
for(int i=1; i<=100; I++)
{
Sum=0;

Sum=sum + I;

}
Cout & lt; return 0;
}
On computers and mobile phones to compile results are 100
I don't know what is going wrong?

CodePudding user response:

Has been solved, the sum=0 should be put in circulation outside

CodePudding user response:

Yes, that's the sum=0 should be written in the book circulation in vitro, otherwise each loop is executed sum=0, before calculation was done not have, only the last 100 will add to, so the result is 100, but when the program is more complex, it is easy to appear this problem, is the variable initialization in the right position, this requires our logical thinking to be clear, can see this article, https://blog.csdn.net/weixin_43956598/article/details/90049508

CodePudding user response:

refer to the second floor Yuan Jun yuan response:
yes, is the sum=0 should be written in the book circulation in vitro, otherwise each loop is executed sum=0, before calculation was done not have, only the last 100 will add to, so the result is 100, but when the program is more complex, it is easy to appear this problem, the initialization is variable in the right position, this requires our logical thinking to be clear, you can see this article, https://blog.csdn.net/weixin_43956598/article/details/90049508

Thank you, just learning, foundation weak,

CodePudding user response:

慢慢来,对于刚学的学者一般会遇到一些问题,我的一些文章你可以看看,对你会有所帮助的
  • Related