C语言 使用 scanf 扫描浮点数和双精度数的最佳方法是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3283162/
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 05:56:30 来源:igfitidea点击:
What is the best way to scan a float and a double with scanf?
提问by Asha
Consider this example:
考虑这个例子:
float a;
double b;
scanf("%f%f", &a, &b); // A
scanf("%Lf%Lf", &a, &b); // B
scanf("%f%Lf", &a, &b); // C
scanf("%f%lf", &a, &b); // D
回答by chanchal1987
You can use
您可以使用
scanf("%f %lf", &a, &b);
scanf type specifiers:
scanf 类型说明符:
- c: Single character: Reads the next character. If a width different from 1 is specified, the function reads width characters and stores them in the successive locations of the array passed as argument. No null character is appended at the end.
- d: Decimal integer: Number optionally preceded with a + or - sign.
- e,E,f,g,G: Floating point: Decimal number containing a decimal point, optionally preceded by a + or - sign and optionally folowed by the e or E character and a decimal number. Two examples of valid entries are -732.103 and 7.12e4
- o: Octal integer.
- s: String of characters: This will read subsequent characters until a whitespace is found (whitespace characters are considered to be blank, newline and tab).
- u: Unsigned decimal integer.
- x,X: Hexadecimal integer.
- c: 单个字符:读取下一个字符。如果指定的宽度不为 1,则该函数读取宽度字符并将它们存储在作为参数传递的数组的连续位置中。最后没有附加空字符。
- d:十进制整数:数字前面可选地带有 + 或 - 符号。
- e,E,f,g,G: 浮点数:包含小数点的十进制数,前面可以有一个 + 或 - 符号,后面可以有 e 或 E 字符和一个十进制数。有效条目的两个示例是 -732.103 和 7.12e4
- o: 八进制整数。
- s:字符串:这将读取后续字符,直到找到空格(空格字符被认为是空白、换行符和制表符)。
- u:无符号十进制整数。
- x,X: 十六进制整数。
Modifiers:
修饰符:
- h: short int (for d, i and n), or unsigned short int (for o, u and x)
- l: long int (for d, i and n), or unsigned long int (for o, u and x), or double (for e, f and g)
- L: long double (for e, f and g)
- h: short int(对于 d、i 和 n)或无符号的 short int(对于 o、u 和 x)
- l: long int (d, i and n), or unsigned long int (o, u and x), or double (e, f and g)
- L: long double (e, f and g)
Source: http://www.cplusplus.com/reference/clibrary/cstdio/scanf/
来源:http: //www.cplusplus.com/reference/clibrary/cstdio/scanf/

