2016-09-23 65 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