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?
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.
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"?
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.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With