gpt4 book ai didi

c++ - 错误输入 C vs C++ cin vs scanf

转载 作者:太空宇宙 更新时间:2023-11-04 06:35:20 24 4
gpt4 key购买 nike

我是 C 的初学者,这是我的问题。在 C++ 中,我会以这种方式查找错误的输入(不是 unsigned int):

long double c;
cin >> c;

if (c == (unsigned int) c) {
cout<<"OK";
}
else
cout<<"NOT OK";

然而,当我现在学习 C 时,我正在尝试以相同的方式进行操作,但它不起作用:

long double c;
scanf("%lf", &c);

if (c == (unsigned int) c) {
printf("OK\n");
}
else
printf("NOT OK\n");

关于如何修复它有什么建议吗?我的任务是仅使用 scanf 而不使用字符串来完成此操作。我不想输入负数和 float 。为什么这行不通?

最佳答案

转换指令 %lf 用于扫描 double

要扫描 long double,请使用 %Lf,大写 L

来自 fscanf (7.21.6.2) 的规范

l (ell) Specifies that a following d, i, o, u, x, X, or n conversion specifier applies to an argument with type pointer to long int or unsigned long int; that a following a, A, e, E, f, F, g, or G conversion specifier applies to an argument with type pointer to double; or that a following c, s, or [ conversion specifier applies to an argument with type pointer to wchar_t.

L Specifies that a following a, A, e, E, f, F, g, or G conversion specifier applies to an argument with type pointer to long double.

关于c++ - 错误输入 C vs C++ cin vs scanf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15647220/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com