在C中创建一个时循环
我刚刚开始学习c,我决定创建一个时循环,以确保我掌握了事情。 这是我的代码:
#include <stdio.h>
void main(){
int num, guess, turns;
num = 13;
guess = getchar();
turns = 0;
while(guess != num){
printf("%d", guess);
++turns;
printf("Turns:\n");
printf("%d", turns);
guess;
}
}
它给了我一个无限的循环。有人可以告诉我我在哪里做错了吗?另外,如果您有任何建议或技巧,请随时离开它们。
I've just started learning C and I've decided to create a while loop to make sure I get the hang of things.
This is my code:
#include <stdio.h>
void main(){
int num, guess, turns;
num = 13;
guess = getchar();
turns = 0;
while(guess != num){
printf("%d", guess);
++turns;
printf("Turns:\n");
printf("%d", turns);
guess;
}
}
It gives me an infinite loop. Can someone please tell me where I went wrong? Also, if you have any suggestions or tips, please feel free to leave them.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
getChar()不会从终端读取,您必须使用:
在while循环中,您必须再次从终端读取一个值(如果猜测是错误的)
getchar() does not read from terminal, you have to use:
In the while loop you have to read a value from terminal again (if the guess is wrong)
我在您的代码中发现了2个问题
首先是您正在使用
试图获得整数输入时,“ getchar”而不是“ scanf”。
第二个问题是,您没有更新while循环内部“猜测”的值(这导致了您的无限循环)。
为了方便起见
这是代码的固定版本,
希望我能帮助:)
I spotted 2 problems in your code
the first is that you are using
"getchar" instead of "scanf" when trying to get an integer input.
And the second problem is that you are not updating the value of "guess" inside the while loop (and that's causing your infinite loop).
For your convenience
here is a fixed version of the code
Hope I could help :)
在您的时循环中,变量
猜测
也不会更改,此行
没有效果。
而且此语句在while循环之前
没有意义,因为函数
getchar
仅读取一个字符并返回字符的内部表示的值。还要根据C标准注意,如果
您的程序可以看以下方式,则无参数的函数主函数。
Within your while loop the variable
guess
is not being changedMoreover this line
does not have an effect.
And this statement before the while loop
does not make a sense because the function
getchar
reads only one character and returns the value of the internal representation of the character.Also pay attention to that according to the C Standard the function main without parameters shall be declared like
Your program can look the following way