gpt4 book ai didi

c - 卡在 C 中的赋值上

转载 作者:太空宇宙 更新时间:2023-11-04 05:38:54 24 4
gpt4 key购买 nike

大家好,我是编程新手,对于我的编程类(class)介绍,我在完成这项作业时遇到了一些问题。我需要一些帮助来解决这个问题,即创建一个输出总降雨量、平均降雨量、最大降雨量和最小降雨量的程序。一切都很好,直到输出最小的降雨量,它一直输出为 0.0。

#include <stdio.h>
#include <stdlib.h>
#define SIZE 5

double getValidRainfall(){
double result;

printf("Enter a rainfall amount: ");
scanf("%lf", &result);

while (result < 0.0){
printf("%.2lf is not a valid rainfall amount.", result);
printf("\nEnter a rainfall amount: ");
scanf("%lf", &result);
}

return result;
}

double calculateTotal (double rainfall[], int size){
double result = 0.0;
int i;
for(i = 0; i < size; i++){
result += rainfall[i];
}
return result;
}

double findLargest(double rainfall[], int size){
double result = 0.0;
int i;
for (i = 0; i < size; i++) {
if(rainfall[i] > result)
result = rainfall[i];
}
return result;
}

// I believe the problem is located right under here and...

double findSmallest(double rainfall[], int size){
double result = 0.0;
int i;
for (i = 0; i < size; i++) {
if(rainfall[i] < result)
result = rainfall[i];
}
return result;
}

// here.. Just can't seem to find the issue that will output the correct smallest
// amount of rainfall.

int main(){
double rainfall[SIZE], totalRainfall, averageRainfall;
double largestRainfall, smallestRainfall;
int i;

for( i = 0; i < SIZE; i++)
rainfall[i] = getValidRainfall();


totalRainfall = calculateTotal(rainfall, SIZE);
averageRainfall = totalRainfall / SIZE;
largestRainfall = findLargest(rainfall, SIZE);
smallestRainfall = findSmallest(rainfall, SIZE);

printf("Thank you\n");
printf("The total rainfall is %.2lf\n", totalRainfall);
printf("The average rainfall is %.2lf\n", averageRainfall);
printf("The largest daily rainfall is %.1lf\n", largestRainfall);
printf("The smallest daily rainfall is %.1lf\n", smallestRainfall);
}

最佳答案

findSmallest 中,您从:

double result = 0.0;

然后你只在降雨量较小时更新它。然而,假设没有任何地方的降雨量为负值,这意味着最终结果仍为 0.0。

要使该算法起作用,您应该以至少与任何实际降雨量一样高的值开始,例如

 if ( size == 0 )
return 0.0;

double result = rainfall[0];

关于c - 卡在 C 中的赋值上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24924747/

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