gpt4 book ai didi

c - 使用 scanf 获取用户的多个输入

转载 作者:行者123 更新时间:2023-11-30 20:26:08 25 4
gpt4 key购买 nike

我这里遇到了问题。我试图从用户那里获取多个输入,并根据他工作的天数计​​算总输入和平均值。例如,如果他工作了10天,当他输入10时,程序会要求他输入10天的工作时间。 iterateArray 数组最多只能保存 30 天,变量 days 保存输入的天数。如何使用 scanf 获取值?

int main(void){

printf("The program calculates the total hours worked during\n");
printf("a specific period and the average length of a day.\n\n");
printf("How many days:");

scanf("%d",&days);


do{
if(i==days){
break;
i++;
}


else{
printf("Enter the working hours for day %d:",++i);
scanf("%f",&iterateArray[0]);
}

}while(i<days);


}

最佳答案

我认为您正在寻找这样的东西:

#include <stdio.h>
#include <stdlib.h>

int main(){

int days, dayCount;
double iterateArray[30], totalWork = 0, averageWork = 0;

printf("The program calculates the total hours worked during\n");
printf("a specific period and the average length of a day.\n\n");
printf("How many days: \n>");

scanf(" %d", &days);

if (days > 30) {
printf("You can't work longer then 30 days!");
exit(0);
}

for(dayCount = 0; dayCount < days; dayCount++) {
printf("Enter the working hours for day %d:", dayCount+1);
scanf(" %lf", &iterateArray[dayCount]);
totalWork += iterateArray[dayCount];
}

averageWork = totalWork / days;

printf("\nThe total hours you worked is: %.2lf\n", totalWork);
printf("The average length of a day is: %.2lf\n", averageWork);


return 0;

}

关于c - 使用 scanf 获取用户的多个输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26696182/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com