【发布时间】:2019-08-31 23:35:24
【问题描述】:
使用 while 循环。 提示用户输入网站的支出并按回车键:
询问他们是否要使用“Y”或“N”选项添加另一个支出(只要“continue_loop”变量等于“Y”)。 (提示:如果用户输入不是“Y”,则循环应该结束。)
验证输入的数据不低于零(查看第 4 章,程序 4-16 以查看输入验证示例)。如果值小于 0,则显示一条消息“值必须大于 0”。
最初用 python 编码,现在必须用 C 重做代码。虽然我在 python 方面表现不错,但我在正常编码方面相当糟糕。
我的大部分代码都已关闭,并且能够以非循环形式正常工作,但我无法弄清楚 while 循环设置以使其验证 y/n 响应。 在核心,我需要以下 for 循环和验证
#include <stdio.h>
int main()
{
int site[20]={};
int i = 0;
int sum;
int loop;
int n;
float avg;
char continue_loop = "y";
printf("Enter Site Expenditure: \n");
scanf(" %d",(site+i));
++i;
printf("Do you want to enter another expenditure? Y/N \n");
scanf(" %c",&continue_loop);
while (continue_loop == "y");
{
printf("Enter Site Expenditure: \n");
scanf(" %d",(site+i));
++i;
printf("Do you want to enter another expenditure? Y/N \n");
scanf(" %c",&continue_loop);
}
printf("\nSite Expenditures \n");
for(loop = 0; loop < i; loop++)
printf(" %d \n", site[loop]);
sum = avg = 0;
for(loop = 0; loop < 3; loop++) {
sum = sum + site[loop];
}
avg = (float)sum / loop;
printf("Average of array values is %.2f ", avg);
if (avg <= 35000)
{
printf ("The average site expenditure is meeting the organization's target goals!");
}
else {
printf("The average site expenditure is NOT meeting the organization's target goals.");
}
return 0;
}
【问题讨论】:
-
尝试在启用警告的情况下进行编译 (
gcc -Wall myprog.c)。另外,请了解在 C 中'y'(char值)和"y"(指向字符串的指针)之间存在很大差异。 -
我已经在这方面工作了一段时间,并在几个站点上进行了示例,但程序在输入字母后立即结束,而不是循环。我通常不是编码人员,所以这让我发疯。
-
如果出现提示时输入
"No Thanks"而不是N会怎样?为什么?scanf如何处理从stdin中提取字符?为什么fgets()是接受用户输入的首选方式?
标签: c validation while-loop