c - 无法读取 C 中的字符

标签 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<=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/

相关文章:

java - 计算字符串中的特定字符 (Java)

c++ - 是否可以将整数的每个数字存储到 char 数组中?

c++ - 在 CreateProcess 的路径中使用 SHGetKnownFolderPath 来运行程序

c - 用recv()确定数据包大小的最佳方法是什么?

c - 我不明白以下 C 代码行

c - 了解 glibc malloc binning 实现

c - 程序过早离开循环

c - 函数返回类型的类型限定符

Char数组声明问题

c++ - 字符串文字 - char 类型之间的模板转换