问题
I am writing simple code for homework. I get one number from user, which is 3.4, when I define it with
scanf("%d",&a)
it takes only 3 and do it that way. I defined a as
int a;
What should I do?
回答1:
Use float
float a;
scanf("%f", &a);
回答2:
I think you are very new to c programming. This is a very simple job. This can be done as:-
float a;
// to input a data in the variable a
scanf("%f",&a);
//to display the stored data
printf("%f\n",a);
//or
printf("%.nf\n",a);//specify value of n
//maximum value of n is 6 also is its default value
//for e.g. printf("%.2f",a); will display decimal number upto two digits after the decimal place
//you can know more about displaying data as
%d: decimal value (int)
%c: character (char)
%s: string (const char *)
%u: unsigned decimal value (unsigned int)
%ld: long int (long)
%f: float value (float or double)
%x: decimal value in Hexadecimal format
%o: decimal value in octal format
For avialabe list of formatting specifications go here
回答3:
%d is for int. 3.4 is not an int type, you can use float.
float x;
scanf("%f", &x);
For detailed information about data types, you can check here: http://en.wikipedia.org/wiki/C_data_types
And also here: http://www.techonthenet.com/c_language/variables/index.php
回答4:
You should define a as
float a;
and replace %d with %f in scanf
scanf("%f", &a);
What should I do?
Read Basics of Formatted Input/Output in C.
回答5:
Its very simple for int variable we use %d format specifier and if we want float we use %f format specifier. Because according to IEEE int and float bit map format are different.
回答6:
You are declaring int a which can take only integer value so what you have to do is make it float which is used for numbers having decimal point
float a; scanf(%f,&a);
来源:https://stackoverflow.com/questions/19078805/how-to-keep-decimals-in-c