C Scanf For Loop off by 1

时间:2016-09-23 20:17:52

标签: c loops

过去几个小时我一直在为学校解决问题而且我无法调试的一个问题让我疯了......

我可以使用scanf这个函数并在数组中输入数字似乎可行,但是printf语句在循环的第一次运行时不起作用。

类似的功能在过去的作业中也做了同样的事情。我可能在某个地方有一个人,但我已经搜索过并没有运气,所以我在这里用一个pastebin链接:

#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;
}

1 个答案:

答案 0 :(得分: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