Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programming Data Types

I am trying to learn C and have come up with the following small program.

#include "stdafx.h"

void main()
{
    double height = 0;
    double weight = 0;
    double bmi = 0;

    printf("Please enter your height in metres\n");
    scanf_s("%f", &height);
    printf("\nPlease enter your weight in kilograms\n");
    scanf_s("%f", &weight);
    bmi = weight/(height * height);
    printf("\nYour Body Mass Index stands at %f\n", bmi);
    printf("\n\n");
    printf("Thank you for using this small program.  Press any key to exit");
    getchar();
    getchar();
}

The program compiles perfectly, however the answer returned by the program does not make sense. If I enter 1.8 for height and 80 for weight, the bmi is like 1.#NF00 which does not make sense.

What am I doing wrong?

like image 319
Matthew Avatar asked Jul 26 '12 14:07

Matthew


People also ask

What are the 5 data types?

Most modern computer languages recognize five basic categories of data types: Integral, Floating Point, Character, Character String, and composite types, with various specific subtypes defined within each broad category.


3 Answers

When using scanf with a double, you must use the %lf specifier, as pointers are not promoted with scanf.

For more info, read the following question: Why does scanf() need "%lf" for doubles, when printf() is okay with just "%f"?

like image 64
Richard J. Ross III Avatar answered Oct 24 '22 08:10

Richard J. Ross III


scanf (and scanf_s) format %f expects pointer to type float.

Simply change the type of your height and weight variables to float to fix this.

like image 34
Didier Trosset Avatar answered Oct 24 '22 09:10

Didier Trosset


I think issue in scanf_s syntaxis, you ommited 3-rd argument, which is size of buffer in bytes. Try following:

scanf_s("%lf", &valueToGet, sizeof(double));
like image 42
spin_eight Avatar answered Oct 24 '22 07:10

spin_eight