【发布时间】:2020-08-08 09:30:11
【问题描述】:
我正在编写一个程序,要求用户猜测计算机正在考虑的数字 1-100。
在程序结束时,当用户猜对了数字时,我试图让程序询问用户是否想再玩一次(重新启动程序)。
为了解决这个问题,我尝试使用do while 循环和char repeat;。循环几乎从程序的开始一直延伸到结束,尽管没有成功。有谁知道我做错了什么?是不是因为talfunktion这个函数导致循环不通过?
代码:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int talfunktion (int tal, int guess, int tries, char repeat);
int main () {
do {
srand(time(NULL));
int tal = rand() % 100 + 1; //tal is the correct value that the code is thinking of
int guess; //guess is the guessed value of the user
int tries = 0; // amount of tries it took until getting correct
char repeat;
printf("Psst, the right number is: %d \n", tal); // remove later, not relevant to uppg.
printf("Im thinking of a number between 1 and 100, guess which!");
printf("\nEnter: ");
scanf("%d", &guess);
guess = talfunktion(tal, guess, tries, repeat);
getchar();
getchar();
return 0;
}
int talfunktion(int tal, int guess, int tries, char repeat) {
do {
if (guess < tal) {
tries++;
printf("\nYour guess is too low, try again!");
printf("\nEnter: ");
scanf("%d", &guess);
}
else if (guess > tal) {
tries++;
printf("\nYour guess is too high, try again!");
printf("\nEnter: ");
scanf("%d", &guess);
}
} while (guess > tal || guess < tal);
if (guess == tal) {
printf("\nCongratulations, that is correct!");
tries++;
printf("\nYou made %d attempt(s)", tries);
printf("\nPlay Again? (y/n)");
scanf("%c", &repeat);
}
} while (repeat == 'y' || repeat == 'Y');
}
【问题讨论】:
-
你的循环中有一个
return 0;,所以它永远不会循环。此外,您有一个}匹配do之后的return没有while子句。 -
此代码无法编译。你不能在 C 中嵌套这样的函数。将 talfunktion 函数移出 main 函数的主体。
-
不要为此使用
do-while。使用while (true)循环,然后在用户拒绝时使用break退出循环。 -
@clay0 函数声明没有意义。函数中不使用其参数try和repeat的值。
-
guess > tal || guess < tal与guess != tal相同。另外(repeat == 'y' || repeat == 'Y')可以简化为(repeat == 'y' )
标签: c function loops while-loop