我需要帮助来创建一个程序,该程序可以接受用户想要的任意多的输入



我正在尝试编写一个处理值集合的程序,我需要将值分组为85+、60-84和小于60,最后求出温度的平均值。我知道我需要使用数组来存储值,我使用do-while循环来请求输入。但当-99被放入时,循环必须退出,我不确定我是否做对了。我也不确定一组输入是如何正确实现的,我需要打印平均值。

#include <stdio.h>

int main(void){
//declare variables
int num[30];
int Cday[30];
int Pday[30];
int Hday[30];
int total;
int total_ave;
double ave;
int NHday, NPday, NCday;


//ask input store into num, then decides if the number goes into which array   
do{
printf("Enter a high temp reading (-99 to quit)>");
scanf ("%d", num);

if(num<=60 && num>=0){
Cday = num;
}
else if(num>=60 && num<=84){
Pday = num;
}
else if(num<=84 && num>=200){
Hday = num;
}

}while(num >=0);

//calculating the average
total = sizeof(num);

for(int i = 0;i< total; i++){
total_ave = total_ave +num[i];
}
ave = total_ave / total;


NHday = sizeof(Hday);
NPday = sizeof(Pday);
NCday = sizeof(Cday);


//printing the final statement once all the values are calculated
printf("Hot days:t %dn", NHday);
printf("Pleasant days:t %dn", NPday);
printf("Cold days:t %dnn", NCday);

printf("The average temperature was %.2f degrees.", ave);




//stops compiling when -99 is entered not collected as information
//
//
return(0);
}

我不确定我是否使用Cday-Pday和Hday的数组正确存储了输入。

我在使用时收到的警告-Wall是

第31、34和37行的指针和整数之间的比较,我得到的另一个错误是我对Cday-Pday和Hday的赋值。所以我想知道我需要改变什么,这样代码才能按照我想要的方式运行。

对于第二个错误,我试图将用户的输入放入这三个类别之一。

据我所知,当用户输入-99时,您想退出,只需检查scanf的返回,如果满足条件,则退出循环:

int stop = scanf("%d", &num) != 1; // scanf wants a pointer
if (stop || (num == -99))
{
break;
}

注意,num必须是单个int,而不是30个ints的数组。

这里你滥用sizeof:

NHday = sizeof(Hday);
NPday = sizeof(Pday);
NCday = sizeof(Cday);

这些行不会返回在每个部分中输入的行的摘要,而是以字节为单位的类型的大小,即:

NHday = sizeof(Hday) = sizeof(int) * 30 = 4 * 30 = 120

不是你想要的,相反,使用NHday作为计数器,不要忘记将NHday初始化为0,以避免意外行为:

int NHday = 0, ...;

最后

//calculating the average
total = sizeof(num);

同样的问题,你不想要sizeof

简化了代码(不需要数组(:

#include <stdio.h>
int main(void)
{
//declare variables
int NHday = 0, NPday = 0, NCday = 0, N = 0, num = 0;
double sum = 0;
do
{
printf("Enter a high temp reading (-99 to quit)>");
int stop = scanf("%d", &num) != 1;
if (stop || (num == -99))
{
break;
}
if (num > 0 && num < 60)
{
NCday++;
}
else if (num >= 60 && num <= 84)
{
NPday++;
}
else if (num > 84 && num <= 200)
{
NHday++;
}
else
{
continue; // Do not increase N
}
sum += num;
} while (++N);
//printing the final statement once all the values are calculated
printf("Hot days:t %dn", NHday);
printf("Pleasant days:t %dn", NPday);
printf("Cold days:t %dnn", NCday);
printf("The average temperature was %.2f degrees.n", sum / N);
return(0);
}

相关内容

最新更新