[英]Reading float using scanf in c
i have a structure which contains a float variable, 我有一个包含float变量的结构,
struct MyStruct{
float p;
}newMyStruct;
And i am reading a value into it using scanf
我正在使用
scanf
向其中读取值
int main(){
scanf("%f",&(newMyStruct.p));
}
The problem is when i print it using printf("%f",newMyStruct.p)
it prints '0.000000'. 问题是当我使用
printf("%f",newMyStruct.p)
打印时printf("%f",newMyStruct.p)
它会打印'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));
我也收到警告,说粗体是双倍的,而格式期望它是浮动的(警告
scanf("%f",&(newMyStruct.p));
语句)。当我将scanf()
语法更改为scanf("%0f",&(newMyStruct.p));
, printf("%0f",newMyStruct.p);
,
printf("%0f",newMyStruct.p);
prints the float value correctly but the compiler gives another warning(something related to precision being 0). 正确打印浮点值,但编译器发出另一个警告(与精度相关的值为0)。 Also
printf("%2f",newMyStruct.p)
prints the float number in some other format. 同样,
printf("%2f",newMyStruct.p)
以其他格式打印浮点数。
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. 所以,我的问题是我如何摆脱所有这些警告并读取一个可以正确打印的适当的float变量。
I dont have access to the laptop i generally code on and hence i cannot provide proper warnings. 我无法访问通常在上面编写代码的笔记本电脑,因此无法提供适当的警告。
Edit: 编辑:
I can't reproduce the problem. 我无法重现该问题。 Everything works as expected when I use the following code compiled with gcc:
当我使用通过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 --version的输出如下:
gcc (Debian 4.7.2-5) 4.7.2
gcc(Debian 4.7.2-5)4.7.2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.