问题
i have a structure which contains a float variable,
struct MyStruct{
float p;
}newMyStruct;
And i am reading a value into it using scanf
int main(){
scanf("%f",&(newMyStruct.p));
}
The problem is when i print it using printf("%f",newMyStruct.p)
it prints '0.000000'. Also i get a warning that says the arugment is double while the format expects it to be float(warning for the scanf("%f",&(newMyStruct.p));
statement).When i change scanf()
syntax to
scanf("%0f",&(newMyStruct.p));
,printf("%0f",newMyStruct.p);
prints the float value correctly but the compiler gives another warning(something related to precision being 0).
Also printf("%2f",newMyStruct.p)
prints the float number in some other format.
So, my question is how do i get rid of all these warnings and read a proper float variable which can be properly printed as well.
I dont have access to the laptop i generally code on and hence i cannot provide proper warnings.
回答1:
Edit:
I can't reproduce the problem. Everything works as expected when I use the following code compiled with gcc:
#include <stdio.h>
struct MyStruct {
float p;
} newMyStruct;
int main() {
scanf("%f", &(newMyStruct.p));
printf("%f\n", newMyStruct.p);
}
The output of gcc --version is as follows:
gcc (Debian 4.7.2-5) 4.7.2
来源:https://stackoverflow.com/questions/19254584/reading-float-using-scanf-in-c