gpt4 book ai didi

c - C语言如何输入字母退出程序

转载 作者:太空狗 更新时间:2023-10-29 15:35:18 24 4
gpt4 key购买 nike

我是 C 编程的新手。我一直在编写这段代码来添加数字,而我只需要这件事的帮助。当我输入字母“q”时,程序应该退出并给出总和。我该怎么做?当前为0号关闭程序。

#include <stdio.h>
int main()

{

printf("Sum Calculator\n");
printf("==============\n");
printf("Enter the numbers you would like to calculate the sum of.\n");
printf("When done, type '0' to output the results and quit.\n");

float sum,num;

do

{
printf("Enter a number:");
scanf("%f",&num);
sum+=num;
}
while (num!=0);


printf("The sum of the numbers is %.6f\n",sum);

return 0;
}

最佳答案

一种方法是将 scanf 行更改为:

if ( 1 != scanf("%f",&num) )
break;

如果他们输入任何无法识别为数字的内容,这将退出循环。

无论您是否采用这种方法,检查 scanf 的返回值并在失败时采取适当的措施仍然是一个好主意。正如您现在所拥有的那样,如果他们输入一些文本而不是数字,那么您的程序将进入无限循环,因为 scanf 会不断失败而不会消耗输入。

关于c - C语言如何输入字母退出程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30857937/

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