1

だから私は、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  

みんな助けて?

4

2 に答える 2

1

f数字の数値ではなく、文字のコードが含まれています (たとえば、「0」のコードはゼロではなく 48 です)。そのため、「奇妙な」出力が得られます。

f数字 (文字) からその数値に変換する必要があります: 計算ではf - '0'代わりに使用fします (内switch)。または、f = f - '0';の前に置くだけswitchです。

f - '0'は有効な変換です。数字のすべての文字コードは、'0' から '9' まで順番に並べられます (ASCII テーブルを見れば簡単にわかります)。したがって、fが含まれている'0'場合f - '0'0(注: 文字ではなく数字)、 is が含まれている場合は==fなどです。'1'f - '0''1' - '0'1

于 2013-11-10T23:15:19.997 に答える