在C中读取字符有困难

在C中读取字符有困难,c,char,C,Char,我有一个程序,我把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<=

我有一个程序,我把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);
}

有任何帮助吗?

f
包含字符代码,而不是数字值(例如,“0”的代码是48,而不是零),这就是为什么会得到“奇怪”输出

您必须将
f
从数字(字符)转换为其数值:在计算中使用
f-'0'
而不是
f
(在
开关内)。或者干脆把
f=f-'0'开关
之前执行code>


f-“0”
是一种有效的转换:数字的所有字符代码都按从“0”到“9”的顺序排列(如果查看ASCII表,很容易看到)。因此,如果
f
包含
'0'
f-'0'
0
(注意:一个数字,而不是一个字符),如果
f
'1'
f-'0'
=
1
,等等。

f
包含字符代码,而不是数字值(例如,“0”代码不是零),这就是为什么会得到“奇怪”的输出

您必须将
f
从数字(字符)转换为其数值:在计算中使用
f-'0'
而不是
f
(在
开关内)。或者干脆把
f=f-'0'开关
之前执行code>


f-“0”
是一种有效的转换:数字的所有字符代码都按从“0”到“9”的顺序排列(如果查看ASCII表,很容易看到)。因此,如果
f
包含
'0'
f-'0'
0
(注意:一个数字,不是一个字符),如果
f
'1'
f-'0'
'1'-'0'
=
1
,等等。

您得到的每个字符都有一个ASCII值。例如,如果您的字符是“1”,那么它的数值是49。也许您想查找函数scanf。它与printf类似,但用于输入。

您得到的每个字符都有一个ASCII值。例如,如果您的字符是“1”,那么它的数值是49。也许您想查找函数scanf。它类似于printf,但用于输入。

我更改了switch语句中的每个f,并得到了以下输出:您插入的数字是:-5078.279785我希望您没有忘记括号,即
(f-'0')*100
,而不是
f-'0'*100
?:)没关系,我只是成功了!非常感谢你!我更改了switch语句中的每个f,得到了以下输出:您插入的数字是:-5078.279785我希望您没有忘记括号,即
(f-'0')*100
,而不是
f-'0'*100
?:)没关系,我只是成功了!非常感谢你!
Introduce a number in the following format (ccc,cc):  

123,45  

The number you inserted is :5456.729980