2016-09-23 82 views
-4

我一直工作在一個問題,學校在過去的幾個小時,一個問題,我不能調試是讓我瘋狂......çSCANF For循環關閉的1

我能得到這個功能並使用scanf將數字輸入到數組中似乎可行,但printf語句在循環的第一次運行時不起作用。

類似的功能在過去的作業中做了同樣的事情。我大概有一次性的地方,但我已經搜查,沒有運氣,所以我在這裏有一個引擎收錄鏈接:

#include <stdio.h> 
#include <stdlib.h> 

#define MAXARRAYSIZE 10 

static float * getGrades (int numGrades); 
static float * getWeights(); 

int main(void) { 

    float * w; 

    w = getWeights(); 

    return 0; 
} 

float * getWeights() { 

    static float weights[MAXARRAYSIZE]; 
    static float temp; 

    printf("Please enter up to %d numbers representing an evaluation scheme!(between 0>100)\n", MAXARRAYSIZE); 

    for (int i = 0; MAXARRAYSIZE > i; i++) { 

      scanf("%f\n", &temp); 

      printf("temp is: %f\n", temp); 

      printf("??????????"); 


      if (100 > temp && temp > 0) { 

        weights[i] = temp; 


        printf("WEIGHTS[i] %f \n", weights[i]); 

      } else if (i < 1) { 

        exit(-1); 

      } else { 
        printf("Invalid input!"); 
        return weights; 
      } 
    } 

    return 0; 
} 
+0

該行是非法的'static float weights [0];'。您的數組未分配。 –

+0

woah woops謝謝!只是改變它,但仍然是同樣的問題,雖然:( – mwcmitchell

+0

它不是一個一個,你正在將數據寫入_nowhere_作爲'靜態浮動權重[0];'不分配任何內存 – ForceBru

回答

0

scanf通話中移除換行符。

#include <stdio.h> 
#include <stdlib.h> 

#define MAXARRAYSIZE 50 

float * getweights() { 
    float* weights = malloc(MAXARRAYSIZE * sizeof(float)); 
    static float temp; 

    printf("Please enter up to %d numbers representing an evaluation scheme!(between 0>100)\n", MAXARRAYSIZE); 

    for (int i = 0; MAXARRAYSIZE > i; i++) 
    { 
     scanf("%f", &temp); 
     printf("temp is: %f\n", temp); 
     printf("??????????"); 

     if (100 > temp && temp > 0) 
     { 
      weights[i] = temp; 
      printf("WEIGHTS[i] %f \n", weights[i]); 
     } 
     else if (i < 1) 
     { 
      exit(-1); 
     } 
     else 
     { 
      printf("Invalid input!"); 
      return weights; 
     } 
    } 
    return weights; 
} 

int main() { 
    float *weightsp; 
    weightsp = getweights(); 
    free(weightsp); 
    return 0; 
} 

$ charlie on work-laptop in ~ 
❯❯ ./eval 
Please enter up to 50 numbers representing an evaluation scheme!(between 0>100) 
10 
temp is: 10.000000 
??????????WEIGHTS[i] 10.000000 
20 
temp is: 20.000000 
??????????WEIGHTS[i] 20.000000 
^C 
+0

@ Jean-FrançoisFabre看到我的答案....這是一個完整的和可驗證的例子。 –

+0

不錯,你花時間修復它。它幫助OP但只有他。那麼這不值得downvote了/ –

+0

謝謝你查爾斯! – mwcmitchell