我试图让它停止但我不太确定该怎么做。我刚开始学习它。当我输入-99时,我希望它停止。
非常感谢任何帮助!
这就是我所拥有的:
#include <stdio.h>
#define SIZE 5
int main(void)
{
int hot=0, pleasant=0, cold=0;
int sum=0, i, temp;
double average;
for(i=0; i<SIZE; i++)
{
printf("Enter temperature %d> (-99 to stop)",i+1);
scanf("%d",&temp);
sum +=temp;
if(temp >= 85)
{
++hot;
}
else if(temp >= 60 && temp <= 84)
{
++pleasant;
}
else
{
++cold;
}
}
average = (double) sum/SIZE;
printf("The Collection of hot days is %d\n",hot);
printf("The Collection of pleasant days is %d\n",pleasant);
printf("The Collection of cold days is %d\n",cold);
printf("The Average temperature is %.2f\n",average);
return(0);
}
答案 0 :(得分:1)
你只需要摆脱循环:
if (temp == -99)
break;
但是您的代码还有其他几个问题,例如,如果您提前退出,则平均计算将会出错。这是一个更正版本,也使用其他循环控制字continue
。
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char *buffer;
size_t buffer_len;
int hot=0, pleasant=0, cold=0;
int sum=0, i=0, temp;
double average;
while(1)
{
printf("Enter temperature %d> (-99 to stop)",i);
buffer = NULL;
getline(&buffer, &buffer_len, stdin);
if (buffer_len == 0 || sscanf(buffer, "%d\n",&temp) != 1)
{
if (buffer)
free(buffer);
printf("Invalid\n");
continue;
}
free(buffer);
if(temp == -99)
break;
sum +=temp;
++i;
if(temp >= 85)
{
++hot;
continue;
}
if(temp >= 60)
{
++pleasant;
continue;
}
++cold;
}
if (i == 0)
{
printf("No temperatures entered\n");
return -1;
}
average = (double)sum / i;
printf("The Collection of hot days is %d\n",hot);
printf("The Collection of pleasant days is %d\n",pleasant);
printf("The Collection of cold days is %d\n",cold);
printf("The Average temperature is %.2f\n",average);
return 0;
}