C编程返回值奇数

时间:2013-05-03 03:03:50

标签: c

我试图在任何地方进行搜索,但这很难说,这很可能是一个简单的修复。基本上,当我通过我的程序来计算一年的平均降雨量时,它会出现一个非常大的数字,但是,我认为这可能只是因为我在做算术错误或者语法错误某种情况,但事实并非如此,当我检查函数返回的值是正确值时。

#include <stdio.h>
#include <string.h>

void getData(float *, float *);

int main()
{
    char state[2], city[81];
    float rainFall[12], outputAverage, *pAverage;

    printf("Name Here\n");
    printf("Please enter the state using a two letter abreviation: ");
    gets(state);
    printf("Please enter the city : ");
    gets(city);
    pAverage = &outputAverage;
    (getData(rainFall, pAverage));
    printf("%.2f", outputAverage);


    return (0);
}

void getData(float *rainFall, float *pAverage)
{
    int i;
    float total;
    for (i=0; i<12; i++)
    {
        printf("Please enter the total rainfall in inches for month %d: ", i+1);
        scanf("%f", &rainFall[i]);
        total += rainFall[i];

    }
    *pAverage = total / 12;



}

5 个答案:

答案 0 :(得分:7)

你需要初始化总数

float total = 0.0;

答案 1 :(得分:2)

  1. 将总数初始化为0
  2. 为什么让它变得复杂?为什么不呢

    返回总数/ 12?

    并称之为

    outputAverage = getData(降雨量)

答案 2 :(得分:0)

这是C编程中的经典问题。您在输入上混合字符串和数字。最好将输入读入字符串,然后使用sscanf正确解析它。

答案 3 :(得分:0)

你有未初始化的变量total这会带来垃圾值,因此你会看到一个非常大的答案。

答案 4 :(得分:0)

改变了你的主..如果你已经了解我做了什么改变,请看看并告诉我?

#include <stdio.h>
#include <string.h>

void getData(float *);

int main(int argc, char*argv[])
{
    char state[3]={0}, city[81]={0};
    float outputAverage;

    printf("Name Here\nPlease enter the state using a two letter abreviation: ");
    scanf("%s",state);
    printf("Please enter the city : ");
    scanf("%s",city);
    getData(&outputAverage);
    printf("The Average Rainfall recorded for the year is %.2f\n", outputAverage);
    return 0;
}

void getData(float *pAverage)
{
    int i;
    float rainFall[12]={0}, total=0;
    for (i=0; i<12; i++)
    {
        printf("Please enter the total rainfall in inches for month %d: ", i+1);
        scanf("%f", &rainFall[i]);
        total += rainFall[i];

    }
    *pAverage = total / 12;
}

但是,您应该使用gets而不是使用fgets,但我忘记了如何解决使用同时fgets从标准输入流中读取输入的问题。

同时初始化total变量,因为您将循环新值添加到该变量中的现有值,该变量不一定会作为首要元素添加到零。所以它可以是任何垃圾值+循环值。

我理解你正在练习指针概念,所以你将浮点数组的地址传递给你的第二个函数但是如果rainfall函数在main中没用,那么更好地限制它在有用的地方< / p>