gpt4 book ai didi

C程序:Why does my guessing game go nuts if you type a string into an int variable

转载 作者:行者123 更新时间:2023-11-30 16:21:16 25 4
gpt4 key购买 nike

如果你在这个脚本中输入一个字符串,程序将完全变得疯狂并保持这样。我的程序首先生成两个整数,一个用于密码,一个用于猜测金额。然后它要求输入你的猜测由于您已经进行了猜测,因此它会将一个数字添加到猜测金额整数中。但是如果你猜的数字大于 100,它会取回一个并告诉你,你犯了错误。然后进入 while 循环。如果你的猜测不是 43,它会循环。在循环中,它告诉你你做错了,你可以输入你的猜测。当然,它会向猜测量变量添加另一个数字。使用前面提到的 if 命令相同,排除高于 100 的数字。然后如果你猜对了,它告诉你这是真的,并告诉你尝试的次数。我已经使用了所有可能的解决方案,但没有一个有效。我只是 C 编程新手,如果你能帮助我,我将非常感激。

#include <stdio.h>
#include <stdlib.h>




int main()
{
int passcode;
int guessamount = 0;
printf("Try to guess the magic passcode:");
scanf("%d", &passcode);
guessamount++;
if(passcode >= 101){
printf("The passcode is too high!It cannot exceed 100\n");
guessamount = guessamount - 1;
}
while(passcode != 43){
printf("The passcode was wrong.Please try again:");
scanf("%d", &passcode);
passcode = (int)passcode;
guessamount++;
if(passcode >= 101){
printf("The passcode is too high!It cannot exceed 100\n");
guessamount = guessamount - 1;
}
}
printf("The passcode is true!You used %d tries!", guessamount);



return 0;
}

最佳答案

scanf 失败时,它不会消耗输入,因此您将被阻塞在无限循环中。

#include <stdio.h>
#include <stdlib.h>

int main() {
int passcode;
int guessamount = 0;

printf("Try to guess the magic passcode:");
scanf("%d", &passcode);

guessamount++;

while (passcode != 43) {
if (passcode >= 101) {
printf("The passcode is too high!It cannot exceed 100\n");
guessamount--;
}

printf("The passcode was wrong.Please try again:");
if (!scanf("%d", &passcode)) {
printf("Invalid value\n");
while (getchar() != '\n');
}

guessamount++;
}
printf("The passcode is true!You used %d tries!", guessamount);



return 0;
}

关于C程序:Why does my guessing game go nuts if you type a string into an int variable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54949302/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com