Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
588 views
in Technique[技术] by (71.8m points)

printf - Reading float using scanf in c

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
", newMyStruct.p);
}

The output of gcc --version is as follows:

gcc (Debian 4.7.2-5) 4.7.2


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...