所以我得到了这个程序,我在其中读取 5 个数字和一个逗号作为字符,并将它们一起表示。我设法做到了,但输出非常奇怪..
代码如下:
#include <stdio.h>
#include <stdlib.h>
int main ()
{
int i=0;
float number = 0.0;
char f;
printf("Introduce a number in the following format (ccc,cc):\n");
for(i=1; i<=6; i++){
f=getchar();
if(f=='\n' && i<6){
printf("the number is not correct.\n");
exit(1); }
if(i==4 && f!=','){
printf("The number doesn't have a comma.\n");
exit(1); }
if(i==4)
continue;
if((f<'0') || (f>'9')){
printf(" %d is not a number .\n", i);
exit(1); }
switch (i)
{
case 1 : number = (f*100);
break;
case 2 : number += (f*10);
break;
case 3 : number = number + f;
break;
case 4: ;
break;
case 5 : number += (f * 0.1);
break;
case 6 : number += (f*0.01);
break;
}
}
printf("The number you inserted is :%f\n",number);
}
数字 123,45 的输出应该是完全相同的数字,但我得到了一个非常尴尬的东西:
Introduce a number in the following format (ccc,cc):
123,45
The number you inserted is :5456.729980
有什么帮助吗?
最佳答案
f
包含字符代码,而不是数字的数值(例如,“0”的代码是 48,而不是零),这就是您得到“奇怪”输出的原因。
您必须将 f
从数字(字符)转换为其数值:在您的代码中使用 f - '0'
而不是 f
计算(在 switch
内)。或者只是将 f = f - '0';
放在 switch
之前。
f - '0'
是一个有效的转换:所有数字的字符代码都按从 '0' 到 '9' 的顺序排列(如果您查看 ASCII 表就很容易看出)。因此,如果 f
包含 '0'
,则 f - '0'
是 0
(注意:一个数字,而不是一个字符),如果 f
为 '1'
,则 f - '0'
为 '1' - '0'
== 1
等
关于c - 无法读取 C 中的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19896456/