嗨,我对编程和编程课程的介绍完全陌生,我对这个作业有一些问题。我需要一些帮助来解决问题,即创建一个输出总降雨量,平均降雨量,最大降雨量和最小降雨量的程序。一切都很好,直到输出的最小降雨量保持输出为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);
}
答案 0 :(得分:4)
在findSmallest
中,您可以开始:
double result = 0.0;
然后,只有在降雨量较小时才更新。但是,假设没有地方有负降雨,这意味着它仍然会以0.0结尾。
要使此算法有效,您应该以至少与实际降雨量一样高的值启动它,例如
if ( size == 0 )
return 0.0;
double result = rainfall[0];
答案 1 :(得分:1)
在findSmallest
中,将result
初始化为一个大数字,大于所有可能性。
E.g,
#include <float.h>
double result = DBL_MAX;
答案 2 :(得分:1)
问题是你在findSmallest函数中将结果初始化为0.0。除非您有负降雨,否则您将永远找不到比这更小的东西。相反,将结果初始化为该函数中的较大值。
答案 3 :(得分:0)
尝试以下:
double findSmallest(double rainfall[], int size){
double result = 0.0;
int i;
for (i = 0; i < size; i++) {
if(i == 0)
result = rainfall[i];
if(rainfall[i] < result)
result = rainfall[i];
}
return result;
代码在问题出现时是不言自明的。
答案 4 :(得分:0)
这是因为findSmallest
以0.0的假设开始,然后寻找负降雨。请使用rainfall[]
中的第一个值作为初始值。