我是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;
}
答案 0 :(得分:2)
一种方法是将<input name="banner" value="<?php if (isset($_POST['banner'])) echo $_POST['banner']; ?>" class="form-control" accept="image/x-png, image/gif, image/jpeg" type="text" placeholder="http://example.com/example.png" required>
行更改为:
scanf
如果输入任何无法识别的数字,它将退出循环。
无论您采用这种方法,检查if ( 1 != scanf("%f",&num) )
break;
的返回值仍然是个好主意,如果失败则采取适当的措施。正如你现在所拥有的,如果他们输入一些文本而不是数字,那么你的程序会进入一个无限循环,因为scanf
在不消耗输入的情况下不断失败。
答案 1 :(得分:1)
它实际上并不像你想象的那么简单。一种方法是检查scanf
返回的值,它返回正确读取的参数数量,如果数字未成功读取,请尝试另一个scanf
来查找退出字符:
bool quit = false;
do
{
printf("Enter a number:");
int numArgsRead = scanf("%f",&num);
if(numArgsRead == 1)
{
sum+=num;
}
else // scan for number failed
{
char c;
scanf("%c",&c);
if(c == 'q') quit = true;
}
}
while (!quit);
答案 2 :(得分:0)
如果你希望你的程序忽略其他输入(就像另一个字母不会退出),它会变得更加复杂。
第一种解决方案是将输入作为字符串读取,将其与您的角色进行比较,然后将其转换为数字。但是,它有许多问题,例如缓冲区溢出等。所以我不推荐它。
然而,有一个更好的解决方案:
char quit;
do
{
printf("Enter a number:");
quit=getchar();
ungetc(quit, stdin);
if(scanf("%f", &num))
sum+=num;
}
while (quit!='q')
ungetc
推回输入上的字符,这样你就可以偷看&#34;偷看&#34;在控制台输入并检查特定值。
您可以使用其他角色替换它,但在这种情况下,它可能是最简单的解决方案,完全符合您的要求。当输入不正确时,它不会尝试添加数字,只会使用q
退出。
答案 3 :(得分:0)
@Shura