2013-05-03 92 views
2

我試圖在任何地方搜索,但這很難說出來,這很可能是一個簡單的修復。基本上,當我瀏覽我的計劃,應該計算一年的平均降雨量時,它會出現一個非常大的數字,但是,我認爲這可能只是我做錯算術或語法錯誤某種形式,但事實並非如此,當我檢查函數返回的值是合適的值時。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; 



} 
+0

CAN你給樣品的輸入和輸出? – 2013-05-03 03:07:40

+2

你正在溢出你的角色數組。例如,你的'state'數組只有兩個字符的空間,但是兩個字符的字符串不可能只適用於兩個字符。 (Pigeonhole原理,如果兩個字符的字符串可以放入兩個字符中,那麼一個字符的字符串也可以放入兩個字符中,但是兩個字符的字符串總數只能等於兩個字符串的數量所以你怎樣才能用兩個字符表示單字符串?因此,你至少需要三個字符的空間來適合兩個字符的字符串。) – 2013-05-03 03:25:02

回答

7

您需要初始化總

float total = 0.0; 
+0

我知道這將是簡單的事情!非常感謝,你救了我一些壓力。 – user2345434 2013-05-03 03:09:27

0

這是在C語言中的經典問題。您正在輸入中混合字符串和數字。您最好將輸入讀入字符串,然後使用sscanf正確解析它。

0

你有未初始化的變量total這是垃圾值,因此你看到一個非常大的答案。

2
  1. 初始化總數爲0
  2. 爲什麼你把它複雜?爲什麼不只是

    返回總數/ 12?

    ,並要求它像

    outputAverage =的getData(降雨)

+0

我喜歡這樣,但我想我需要練習指針,這基本上是我明天期末考試的複習,​​所以我正在準備一些複雜的練習。 – user2345434 2013-05-03 03:10:45

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功能在主有用的,更好的限制相同的地方將是有益的