2013-03-27 85 views
-1

我的某個函數有問題。下面是代碼:在if語句中使用for循環和數組時遇到問題

include <stdio.h> 
include <math.h> 
include <stdlib.h> 

int inputAmount(int i); 

void inputFahrs(double data[ ], int j); 

double fahrToCels (double data[ ], int j); 

void outputFahrs(double data [ ], int numFahrs); 

void outputAverage(double data[ ], int numFahrs); 

void outputHighLows(double data[ ], int numFahrs); 

void outputGrads(double data[ ], int numFahrs); 

int main (void) 
{ 
    int i, j, numFahrs; 
    double data[i], *ptr=&data[i]; 
    i=inputAmount(i); 
    printf("%d\n\n", i); 
    inputFahrs(&data[i], i); 
    data[j]=fahrToCels(&data[i], j); 
    printf("%.1f", data[j]); 
    return 0; 
} 

int inputAmount(int i) 
{ 
    printf("Please enter the amount of vaues you would like to use.\n\n"); 
    scanf("%d", &i); 
    while(i<1 || i>25) 
    { 
     printf("Value is out of range. Please enter another value.\n\n"); 
     scanf("%d", &i); 
    }  
    return i; 
} 

void inputFahrs(double data[ ], int i) 
{ 
    int j; 
    printf("Please enter temperature values in the range of -175 to 175 degrees F.\n\n"); 
    for(j=0;j<i;j++) 
    { 
     scanf("%f", &data[j]); 
     if (data[j]< -175 || data[j]>175) 
     { 
      printf("Temperature value is out of range. Please re-enter"); 
      scanf("%f", &data[j]); 
     } 
    }  
} 

double fahrToCels (double data[ ], int j) 
{ 
    int i; 
    printf("TEST"); 
    for(j=1;j<=i;j++) 
    { 
     data[i]=(((data[i])-32)*(5.0/9.0)); 
    } 
    return data[i]; 
} 

基本上在我的代碼的問題是,它完全跳過if聲明。我希望程序通過for循環,如果用戶輸入的值超出範圍,我希望if語句啓動。在for循環內但在if語句之後的打印語句正常工作,所以肯定有問題。我也嘗試了while循環代替if

+1

小對象 - 在這個代碼怎麼回事。 – 2013-03-27 02:44:07

+0

條件本身似乎沒問題,但你確實需要檢查指標。還有一點是,你不需要在if語句中獲得新的輸入,遞減'j'應該足夠了。 – Motasim 2013-03-27 02:58:28

+0

'我'不是初始化順便說一句。 [這段代碼導致了我的無限循環](http://liveworkspace.org/code/2gWpzh$20)。 – 2013-03-27 04:09:52

回答

0

問題是你與

Ĵ

迭代循環,下標檢查條件使用j個標在

將工作

的scanf( 「%F」,&數據[j]的)

如果(數據[j]的< -175] | |數據[j]> 175)

應該工作。因爲數據[i]是不是一個可能的下標值,由於i是陣列尺寸

和爲什麼你使用的線

data[i]=data[i]; 

+0

我,j是個問題。但它將數據輸入到數據[i]中,並在if語句中比較數據[i]。所以你的回答並不是真正的問題。 – TieDad 2013-03-27 02:39:06

+0

問題是數據[I]不存在,因爲有從0僅標爲i-1中,由於i是陣列的尺寸 – 2013-03-27 02:41:34

+0

@EvanLi:'數據[I]'是不是一個有效的內存位置,因爲它是在數組邊界之外。 – Jack 2013-03-27 02:42:36

-1

我想這是因爲您正在使用i索引掃描和存儲數據,索引是傳遞給函數的數組的大小,而不是當前元素的索引,該索引存儲在j中。它應該是:

scanf("%f", &data[j]); 
    .. 

另外,爲什麼你在你的比較for循環j <= i - 1j < i聽起來更簡單。

0
void inputFahrs(float data[],int i) 
{ 
    int j; 
    printf("Please Enter values in the range of -175 to 175\n"); 
    for(j=0;j<i;j++) 
    { 
      scanf("%f",&data[j]); 
      if(data[j]<-175 || data[j]>175) 
      { 
        printf("value is out of range. Enter correct value\n"); 
        j--; 
      } 
    } 
} 

這一個正常工作

+0

你甚至還能達到這個功能嗎? [這段代碼導致我的死循環](http://liveworkspace.org/code/2gWpzh%2420)。 – 2013-03-27 04:35:12

+0

@AnishRam:你犯了同樣的錯誤。在呼叫聲明中使用&data [i]而不是'data' – 2013-03-27 09:47:48

+0

請刪除此答案並將其與您的上一個答案結合使用。 – 2013-03-27 13:45:27