问题描述
我有一个包含浮点变量的结构,
i have a structure which contains a float variable,
struct MyStruct{
float p;
}newMyStruct;
我正在使用 scanf
int main(){
scanf("%f",&(newMyStruct.p));
}
问题是当我使用 printf("%f",newMyStruct.p)
打印它时,它会打印 '0.000000'.我还收到一条警告,说参数是双倍的,而格式期望它是浮动的(警告 scanf("%f",&(newMyStruct.p));
语句).当我将 scanf()
语法更改为scanf("%0f",&(newMyStruct.p));
,printf("%0f",newMyStruct.p);
正确打印浮点值,但编译器给出另一个警告(与精度为 0 相关的内容).此外,printf("%2f",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 toscanf("%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.
推荐答案
我无法重现该问题.当我使用以下用 gcc 编译的代码时,一切都按预期工作:
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);
}
gcc --version 的输出如下:
The output of gcc --version is as follows:
gcc (Debian 4.7.2-5) 4.7.2
这篇关于在c中使用scanf读取浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!