C 终止循环的另一种方法?
我在课堂上学习循环,对于其中一个实验室,我必须找出一种方法,让用户输入一个未指定数量的整数来计算平均数。我知道我可以让用户输入要平均的整数数,以便循环终止,如下所示:C 终止循环的另一种方法?,c,C,我在课堂上学习循环,对于其中一个实验室,我必须找出一种方法,让用户输入一个未指定数量的整数来计算平均数。我知道我可以让用户输入要平均的整数数,以便循环终止,如下所示: int count = 0, value = 0, sum = 0, numberofintegers = 0; double avg = 0; printf("enter the number of integers you wish to average\n"); scanf("%d",&numberofinte
int count = 0, value = 0, sum = 0, numberofintegers = 0;
double avg = 0;
printf("enter the number of integers you wish to average\n");
scanf("%d",&numberofintegers);
//loop
while (count < numberofintegers)
{
printf("enter a positive integers\n");
scanf("%d",&value);
sum = sum + value;
count = count + 1;
}
avg = (double) sum/count;
int count=0,value=0,sum=0,numberofintegers=0;
双平均值=0;
printf(“输入要平均的整数数\n”);
scanf(“%d”和numberofintegers);
//环路
while(count
因此,基本上我可以让用户输入要平均的整数数,以便循环终止,但必须有另一种方法使循环终止,而不需要用户输入它?通常,您会使用一个预先确定的“非法”数,如(比如-1)
scanf
返回成功条目的数量
这可能会解决你的问题
#include<stdio.h>
int main(void)
{
int number, total = 0, count = 0;
char c;
printf("Enter a number to continue, a character to exit\n");
while (scanf("%d", &number) == 1)
{
total+= number;
count++;
}
/* You need to handle the case where no valid input is entered */
(count > 0) ? printf("Average : %.2f\n", (float)total / count) : printf("No valid numbers entered\n");
/* I have casted the average to float to keep the precision*/
while (getchar() != '\n')
;;
printf("Press any key to continue..");
getchar();
return 0;
}
#包括
内部主(空)
{
整数,总数=0,计数=0;
字符c;
printf(“输入一个数字以继续,输入一个字符以退出\n”);
while(scanf(“%d”,&number)==1)
{
总数+=数量;
计数++;
}
/*您需要处理没有输入有效输入的情况*/
(计数>0)?printf(“平均值:%.2f\n”,(浮动)总计/计数):printf(“未输入有效数字”);
/*为了保持精度,我已将平均值设置为浮动*/
而(getchar()!='\n')
;;
printf(“按任意键继续…”);
getchar();
返回0;
}
缺点是,如果用户反复按下
Enter键
,scanf将继续提示输入。事实上,您可能希望将scanf
替换为fgets
。看看。如果您确定用户没有输入太多的数字,请使用字符串。
字符串的长度,您可以根据自己选择,并使用空格将其拆分以获得数字要终止循环而不获取numberofintegers值吗?
printf(“输入正整数\n”)代码>那里的关键词是“积极”。不要询问用户要输入多少号码。在用户输入负数之前,只需计算输入的数字数量。@user3386109:我假设用户非常迟钝,以至于不知道如何输入负整数。很抱歉,还有更多的代码是确定用户是否输入了大于0的值的if/else语句。不管怎样,这在这个问题上无关紧要。在这种情况下,我想知道如何在没有“numberofintegers”变量的情况下终止循环。当用户输入负数时终止循环。见约翰的答案。John的答案要求-1来终止循环,我允许用户输入任何负数来终止循环。sjsam在用户输入(非数字)垃圾时终止循环的解决方案也是有效的。请提供示例代码来演示和澄清您的观点。
#include<stdio.h>
int main(void)
{
int number, total = 0, count = 0;
char c;
printf("Enter a number to continue, a character to exit\n");
while (scanf("%d", &number) == 1)
{
total+= number;
count++;
}
/* You need to handle the case where no valid input is entered */
(count > 0) ? printf("Average : %.2f\n", (float)total / count) : printf("No valid numbers entered\n");
/* I have casted the average to float to keep the precision*/
while (getchar() != '\n')
;;
printf("Press any key to continue..");
getchar();
return 0;
}