在c中使用scanf读取float

问题描述 投票:0回答:2

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

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)
以其他格式打印浮点数。

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

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

c printf string-formatting scanf
2个回答
5
投票

编辑:

我无法重现该问题。当我使用用 gcc 编译的以下代码时,一切都按预期工作:

#include <stdio.h>

struct MyStruct {
  float p;
} newMyStruct;

int main() {
  scanf("%f", &(newMyStruct.p));
  printf("%f\n", newMyStruct.p);
}

gcc --version 的输出如下:

gcc(Debian 4.7.2-5)4.7.2


0
投票

使用

scanf("\n%f",&(newMyStruct.p));

下面的代码可能会自动读取空值。

scanf("%f",&(newMyStruct.p));
© www.soinside.com 2019 - 2024. All rights reserved.