问题描述
如果按下击键,我写了一个简单的循环来增加变量。
现在尝试输入时
abc
我得到输出
1233
我想要到达
123
我该怎么办? ??????
我知道问题是当我打印循环时回到第一个语句i ++并增加i变量的值。
请帮助。
我尝试过:
I have written a simple loop to increment a variable if a keystroke is pressed.
Now when it try input
abc
I get the output
1233
I want to get till
123
how can i do this?????????
I know the problem is when i is printed loop goes back to first statement i++ and increases value of i variable.
Kindly help.
What I have tried:
#include<iostream>
using namespace std;
int main()
{
int i=0;;
int c;
while( (c=getchar())!=EOF)
{
i++;
if(c=='\n')
{
i--;
}
cout<<i;
}
getchar();
return 0;
}
推荐答案
Input Expected output Actual output
1 2 1
2 4 4
3 6 9
4 8 16
然后很明显问题出在将它加倍的位 - 它不会将自身加到自身上,或者将它乘以2,它会将它自身相乘并返回输入的平方。
所以,你可以查看代码和很明显,它在某处:
Then it's fairly obvious that the problem is with the bit which doubles it - it's not adding itself to itself, or multiplying it by 2, it's multiplying it by itself and returning the square of the input.
So with that, you can look at the code and it's obvious that it's somewhere here:
int Double(int value)
{
return value * value;
}
一旦你知道可能出现的问题,就开始使用teh调试器找出原因。在你的行上设一个断点:
Once you have an idea what might be going wrong, start using teh debugger to find out why. Put a breakpoint on your line:
while( (c=getchar())!=EOF)
并运行你的应用程序。在执行代码之前,请考虑代码中的每一行应该做什么,并将其与使用Step over按钮依次执行每一行时实际执行的操作进行比较。它符合您的期望吗?如果是这样,请转到下一行。
如果没有,为什么不呢?它有何不同?
这是一项非常值得开发的技能,因为它可以帮助你在现实世界和发展中。和所有技能一样,它只能通过使用来改善!
是的,我可能会告诉你问题是什么 - 但这并不难做到,你会在同一时间学到一些非常有价值的东西!相反,我会给你一个提示:看看你处理完最后一个数字后会发生什么......
and run your app. Think about what each line in the code should do before you execute it, and compare that to what it actually did when you use the "Step over" button to execute each line in turn. Did it do what you expect? If so, move on to the next line.
If not, why not? How does it differ?
This is a skill, and it's one which is well worth developing as it helps you in the real world as well as in development. And like all skills, it only improves by use!
Yes, I could probably tell you what "the problem" is - but it's not difficult to do this yourself, and you will learn something really worthwhile at the same time! Instead, I'll give you a hint: watch what happens when you have processed the last digit...
这篇关于如何获得输出2而不是3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!