Why can’t I get a read on that Cyborg?

Asked

Viewed 104 times

1

I’m new to programming; that’s the question:

Having as input the name, height and sex (M or F) of a person, calculate and show your ideal weight, using the following formulas:

• for men: ideal weight = (72.7 * height) - 58

• female: ideal weight = (62.1 * height) - 44.7

However, in the code, it does not read the Male and Female data.

I wonder why I can’t do the reading?

The scanf is the best way to take character readings?

Thank you very much.

inserir a descrição da imagem aqui

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

int main(void) {

    setlocale(LC_ALL,"");

    unsigned char nome[50],gen;
    float alt,resultado;


    printf("Qual o seu nome?\n");
    scanf("%s",&nome);

    printf("Qual o seu genero [M] ou [F] para feminino?\n");
    scanf("%c",&gen);

    printf("Qual a sua altura?\n");
    scanf("%f",&alt);

    if (gen == 'M') { 
        resultado == (72.7 * alt) - 58;
        printf("O seu peso ideal é: %.1f",resultado);
    } else if (gen == 'F') {
        resultado == (62.1 * alt) - 44.7;
        printf("O seu peso ideal é: %.1f",resultado);
    } else {
        printf("\n letra inválida, informe  M ou F\n");
    }
}

1 answer

3


The function scanf automatically consumes blanks, prior to conversion, from the standard input stream stdin when the conversion specifier is not one of the following: %c, %n and %[].

This means that after

scanf("%s", nome); // remova '&', esse é o jeito correto de ler uma string com scanf

there is a line break character \n in the input stream, waiting to be consumed. As your next command is

scanf("%c", &gen);

the function scanf will store the line break character in gen.


To resolve, use a blank space before the conversion specifier %c

scanf(" %c", &gen);

White space tells function scanf to skip the first blank space, and the first character other than a blank space will be read with the conversion specifier %c.

In addition, both assignments to the resultado are wrong. The assignment operator is only the character =

resultado = (72.7 * alt) - 58;
...
resultado = (62.1 * alt) - 44.7;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.