Range not respected in a function?

This is a very simple program I made to test some stuff with structs which I'm new with.

If you try to execute the program, you'll notice that the first if in the void function is ignored (or maybe not satisfied) even when 19 <= BMI <= 25

#include <stdio.h>
#include <string.h>
#include <ctype.h>
typedef struct {
        char name[50];
        float weigth;
        float heigth;
        float BMI;
} subjects;
void check_BMI(subjects Candidate)
{
        if (Candidate.BMI >= 19 && Candidate.BMI <= 25)
                puts("Subject is probably in good shape");
        else
                puts("Subject might not be in good shape");
}
int main()
{
        subjects Candidate;
        Candidate.BMI = Candidate.weigth/(Candidate.heigth * Candidate.heigth);
        puts("Insert subject's name: ");
        fgets(Candidate.name, 50, stdin);
        puts("Insert subject's weigth (in kg): ");
        scanf("%f", &Candidate.weigth);
        puts("Insert subject's heigth (in m): ");
        scanf("%f", &Candidate.heigth);
        check_BMI(Candidate);
        return 0;
}

What could be my mistake?


You're doing it in the wrong order:

    Candidate.BMI = Candidate.weigth/(Candidate.heigth * Candidate.heigth);
    puts("Insert subject's name: ");
    fgets(Candidate.name, 50, stdin);
    puts("Insert subject's weigth (in kg): ");
    scanf("%f", &Candidate.weigth);
    puts("Insert subject's heigth (in m): ");

You can't calculate the BMI as ratio of two numbers that haven't yet been entered. How is that supposed to work?

Move the BMI calculating line to a place after you've entered all numbers, and before you print the result.


You have

subjects Candidate;

which is uninitialized. Right after the declaration, you use

Candidate.BMI = Candidate.weigth/(Candidate.heigth * Candidate.heigth);

which calculates Canditate.BMI with the uninitialized values (garbage: Candidate.weigth , Candidate.heigth ). This leads to Undefined Behavior.

Fix the problem by moving

Candidate.BMI = Candidate.weigth/(Candidate.heigth * Candidate.heigth);

just before

check_BMI(Candidate);

so that the values are initialized when calculating Canditate.BMI .

链接地址: http://www.djcxy.com/p/22886.html

上一篇: 如何显示数组?

下一篇: 函数中不受尊重的范围?