C逗号是scanf中的中断整数

  • 本文关键字:中断 整数 scanf c scanf
  • 更新时间 :
  • 英文 :


下面的代码要求用户输入一个数字,后跟一个运算符。只要不使用逗号,它就可以工作。例如,

快乐之路

6000+2000 will output 6000.000 + 2000.000 

意外输出

6,000+2,000 will output 6.000 , 0.000

scanf是否可以在使用逗号时以某种方式将值视为浮点值?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
int main(int argc, char *argv[]) 
{
char operatorFound;
float num1,num2, calcValue;
printf("Please enter a simple expression (ie: 2+2):" );
scanf("%f%c%f", &num1, &operatorFound, &num2);
printf("%fn%cn%f", num1, operatorFound, num2); 
return 0;
}

在Linux下,可以通过相应地设置区域设置来调整scanf。请参阅scanf Linux文档

对于十进制转换,一个可选的引号字符('(。这指定输入号码可以包括LC_NUMERIC定义的千位分隔符当前区域设置的类别。(请参见setlocale(3(。(这个引号字符可以在"*"赋值之前或之后-抑制特性。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <locale.h>
int main(int argc, char *argv[]) 
{
char operatorFound;
float num1, num2, calcValue;
// Use en_US.UTF-8 to separate groups of thousands, many other countries use a period instead, and some countries separate thousands groups with a space
setlocale(LC_NUMERIC, "en_US.UTF-8");
puts("Please enter a simple expression (ie: 2+2):" );

// Notice the use of a single quote
if (scanf("%'f %c%'f", &num1, &operatorFound, &num2) == 3) { 
printf("%fn%cn%f", num1, operatorFound, num2); 
} else {
puts("Unable to process input");
}
return 0;
}

扫描时,输入C使用逗号作为字符。

如果只输入6.00,它仍然会打印6.000.000,因为它将逗号作为第二个输入。

因此,您应该使用句点对于浮动

所以在测试之后。我发现我的编译器有缺陷。当我在Linux GCC上测试时,所有的答案都是有效的。

如果我输入

6000+2000将输出8000

6000+2000将输出8000

6000+2000将输出8000

6000+2000将输出8000

6000+2000将输出8000

等等

感谢大家调查此事并帮助我完成

最新更新