我刚刚开始学习C,我决定创建一个while循环来确保我掌握了一些东西。这是我的代码:
#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;
}
}
它给了我一个无限循环。谁能告诉我我哪里做错了?另外,如果你有任何建议或提示,请随时留下。
getchar()不能从终端读取,必须使用:
scanf(" %d", &guess);
在while循环中,你必须再次从终端读取值(如果猜错了)
while(guess != num){
printf("Turns:n");
printf("%d", guess);
++Turns;
scanf(" %d", &guess);
}
printf("%d is the correct guess", guess);
我在你的代码中发现了两个问题首先是你在使用"getchar"而不是"scanf"当尝试获取整数输入时。
第二个问题是你没有更新"guess"的值在while循环内(这会导致无限循环)
为了您的方便下面是代码
的固定版本void main() {
printf("start n");
int num, guess, turns;
num = 13;
scanf("%d", &guess);
turns = 0;
while(guess != num){
printf("your guess was : %d n", guess);
++turns;
printf("Turns:");
printf("%d n", turns);
scanf("%d", &guess);
}
}
希望我能帮上忙:)
在while循环中,变量guess
未被更改
while(guess != num){
printf("%d", guess);
++turns;
printf("Turns:n");
printf("%d", turns);
guess;
}
而且这一行
guess;
不起作用
while循环前的语句
guess = getchar();
没有意义,因为函数getchar
只读取一个字符并返回该字符的内部表示的值。
还需要注意的是,根据C标准,不带参数的main函数应该像
这样声明。int main( void )
你的程序可以像下面这样
#include <stdio.h>
int main( void )
{
unsigned int num = 13;
unsigned int turns = 0;
unsigned int guess = 0;
puts( "Try to guess the number I thought." );
printf( "Enter a non-negative number: " );
while( scanf( "%u", &guess ) == 1 && guess != num )
{
printf( "%u is not my number.n", guess );
++turns;
printf( "It is your %u attemptn", turns );
printf( "nEnter a non-negative number: " );
}
if ( guess == num )
{
printf( "nYou have guessed the number using %u guesses.n", turns );
}
else
{
printf( "nYou have not guessed the number using &u guesses.n", turns );
}
}