C语言 在c中使用scanf读取浮点数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19254584/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 07:40:09  来源:igfitidea点击:

Reading float using scanf in c

cprintfstring-formattingscanf

提问by thunderbird

i have a structure which contains a float variable,

我有一个包含浮点变量的结构,

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'. 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.

问题是当我使用printf("%f",newMyStruct.p)它打印它时会打印“0.000000”。此外,我收到一条警告,指出参数是双精度的,而格式预计它是浮点数(该scanf("%f",&(newMyStruct.p));语句的警告)。当我将scanf()语法更改为 时 scanf("%0f",&(newMyStruct.p));,会printf("%0f",newMyStruct.p);正确打印浮点值,但编译器给出了另一个警告(与精度为 0 相关的内容) )。还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.

所以,我的问题是如何摆脱所有这些警告并读取一个可以正确打印的适当浮点变量。

I dont have access to the laptop i generally code on and hence i cannot provide proper warnings.

我无法访问我通常在其上编码的笔记本电脑,因此我无法提供适当的警告。

回答by Joshua Swank

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