C语言中简单程序的奇怪输出
可能重复:C语言中简单程序的奇怪输出,c,C,可能重复: 有人能告诉我我的代码出了什么问题以及为什么它会产生这个输出吗。当我输入“是”时,输出会变得很奇怪……我希望我的代码能够正确地处理Y/Y和N/N……但我希望代码中键入的任何其他内容都会显示“无效输入。请重试”。是否有人可以编辑我的代码,使其可以这样做 代码: 您输入字符串“yes”,但是您只从该字符串中读取一个字符,在输入中留下“es”。然后,scanf调用尝试读取该字符,由于它不是一个数字,因此将失败,使字母仍保留在输入缓冲区中。您需要另一个while循环围绕getchar,保持循
有人能告诉我我的代码出了什么问题以及为什么它会产生这个输出吗。当我输入“是”时,输出会变得很奇怪……我希望我的代码能够正确地处理Y/Y和N/N……但我希望代码中键入的任何其他内容都会显示“无效输入。请重试”。是否有人可以编辑我的代码,使其可以这样做 代码:
您输入字符串
“yes”
,但是您只从该字符串中读取一个字符,在输入中留下“es”
。然后,scanf
调用尝试读取该字符,由于它不是一个数字,因此将失败,使字母仍保留在输入缓冲区中。您需要另一个while循环围绕getchar,保持循环直到其为y或n,每次都不是,告诉他们它的notStackOverflow不起作用,把你不起作用的代码贴在这里,让别人帮你编辑它,这样它就会起作用。这不是一个家庭作业完成网站或代码编写服务。您只需发布相关代码,并询问有关如何解决问题的具体问题。这里有关于要问什么类型问题的更多信息,以及关于如何以提高您获得帮助机会的方式提问的一些提示。祝你好运。我如何解决这个问题…我必须使用getchar()来完成这个任务。那么,在这种情况下,你认为我的教授会让这个奇怪的输出滑动吗,因为她特别指定使用getchar()?scanf将返回它读取的值的整数计数。它也没有被检查。如果它按照请求读取一个整数,则应返回1。因此,在请求数字的位置单击return也会导致问题,因为num
的值不会更改。也许在循环中将num
设置为0会使它更容易理解。你的导师是要求“是”和“否”被接受为输入,还是要求只接受单个字符的响应,如Y
和N
?@mikemikee答案真的就在眼前。。。你写了三个字母作为输入,但只读了一个字母……考虑一下做一个getchar
并使用它。然后在循环中执行更多的getchar
调用,直到得到行尾字符。你的测试可以看到你得到的是否正确。您可能会考虑如果他们键入“”然后键入“y”或“n”,会发生什么,因此您必须使输入代码更智能。
int main(){
unsigned num;
char response;
do{
printf("Please enter a positive integer greater than 1 and less than 2000: ");
scanf("%d", &num);
if (num > 1 && num < 2000){
printf("All the prime factors of %d are given below: \n", num);
printPrimeFactors(num);
printf("\n\nThe distinct prime factors of %d are given below: \n", num);
printDistinctPrimeFactors(num);
}
else{
printf("\nSorry that number does not fall between 1 and 2000.\n");
}
printf("\n\nDo you want to try another number? Say Y(es) or N(o): ");
getchar();
response = getchar();
}
while(response == 'Y' || response == 'y'); // if response is Y or y then program runs again
printf("Thank you for using my program. Good Bye!\n\n"); //if not Y or y, program terminates
return 0;
}
Please enter a positive integer greater than 1 and less than 2000: 1600
All the prime factors of 1600 are given below:
2 2 2 2 2 2 5 5
The distinct prime factors of 1600 are given below:
2 5
Do you want to try another number? Say Y(es) or N(o): yes
Please enter a positive integer greater than 1 and less than 2000: All the prime factors of 1600 are given below:
2 2 2 2 2 2 5 5
The distinct prime factors of 1600 are given below:
2 5
Do you want to try another number? Say Y(es) or N(o): Thank you for using my program. Good Bye!