Types of Programming Data

I am trying to learn C and came 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 fine, but the answer returned by the program does not make sense. If I enter 1.8 for height and 80 for weight, bmi is like 1. # NF00, which doesn't make sense.

What am I doing wrong?

+7
source share
6 answers

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

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

+10
source

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

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

+11
source

I think the problem is in the scanf_s syntax, you missed the 3rd argument, the size of the buffer in bytes. Try the following:

 scanf_s("%lf", &valueToGet, sizeof(double)); 
+4
source

The drawback of scanf () and printf () is that it requires a very strict format, any mismatch between the control line and the argument can lead to a serious error, which makes your input or output completely meaningless. And this mistake is often made by beginners.

+3
source

If you use the % f format specifier, then you should use the float data type instead of double.

+2
source

The problem is this:

 format '%f' expects argument of type 'float*', but argument 2 has type 'double*' 

There are two ways to deal with this:

  • Or variables should be float :

     double height = 0; --> float height = 0; double weight = 0; --> float weight = 0; double bmi = 0; --> float bmi = 0; 
  • or format specifier must match double .

     scanf_s("%f", &height); --> scanf_s("%lf", &height); scanf_s("%f", &weight); --> scanf_s("%lf", &weight); printf("\nYour Body Mass Index stands at %f\n", bmi); | V printf("\nYour Body Mass Index stands at %lf\n", bmi); 
0
source

All Articles