您好,目前我正在努力开发一个项目,但我遇到了障碍,我已经盯着这段代码几个小时了,无法弄清楚发生了什么
我的主要问题是找到用户输入的数组的最小值...我能够获得最大值和输出,但由于某种原因,我无法得到最小值输出正确的结果。我一直都是0.0 ....
#include <stdio.h>
#include <stdlib.h>
#define SIZE 5
double getValidRainfall() {
double result;
printf("\nEnter a rainfall amount: ");
scanf("%lf", &result);
while (result < 0.0) {
printf("%.2lf is not a valid rainfall amount.", result);
printf("\nEnter another 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;
}
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;
}
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);
// outputs
printf("\nThank you.\n");
printf("The total rainfall for these 5 days 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);
system("pause");
}
答案 0 :(得分:2)
在下面的函数中,将result
分配给可能的最大值或者从数组本身分配一个,否则,它将给出错误的结果,因为0.0
将始终小于数组中的任何值(考虑到降雨量a + ve数量)&amp;这种情况总是错误的。
double findSmallest(double rainfall[], int size) {
double result = DBL_MAX; // or double result = rainfall[0], if size >= 1;
int i;
for (i = 0; i < size; i++) {
if (rainfall[i] < result)
result = rainfall[i];
}
return result;
}
答案 1 :(得分:0)
显然,所有降雨条目都需要0.0
将result
初始化为一个极高值,而不是零。
答案 2 :(得分:0)
您需要将结果变量初始化为数组中的第一个元素或高于所有值的值(第一个方法更有效)。由于您将其初始化为0.0,除非值为负,否则将保持为0.0。因此我建议:
double result = rainfall[0];