带有char的Switch语句总是在C中返回0

时间:2015-03-16 15:20:40

标签: c char switch-statement

由于某种原因,switch语句总是返回零值,输入值在开关中正确匹配,但由于某种原因,返回值默认为零,使colorx = 0.感谢高级帮助。

#include <stdio.h>
#include <stdlib.h>
#include <math.h>


double  Band(char code);

int main()
{
char     code1, code2, code3, code4, code5;     
double  resistance;
double  color1 = 0, color2 = 0, color3 = 0, color4 = 0, color5 = 0;  
int     flag, Lines, i;
FILE *ifp, *ofp;
//char outputFilename[] = "C:\\Users\Kevin\\Desktop\\resistorOutput.txt";
ifp = fopen("C:\\Users\\Kevin\\Desktop\\resistorInput.txt", "r");
//ofp = fopen("C:\\Users\\Kevin\\Desktop\\resistorOutput.txt", "w");

rewind(ifp);
fscanf(ifp, "%d\n", &Lines);
for(i=1; i<=Lines; i++)
{
printf("Lines = %d\n", Lines);
fscanf(ifp, "%c%c%c%c%c\n", &code1, &code2, &code3, &code4, &code5);
printf("code1 = %c\n", code1);
printf("code2 = %c\n", code2);
printf("code3 = %c\n", code3);
printf("code4 = %c\n", code4);
printf("code5 = %c\n", code5);
color1 = Band( code1);
color2 = Band( code2);
color3 = Band( code3);
color4 = Band( code3);
color5 = Band( code3);
printf("color1 = %d\n", color1);
printf("color2 = %d\n", color2);
printf("color3 = %d\n", color3);
printf("color4 = %d\n", color4);
printf("color5 = %d\n", color5);
}
}


double Band(char code)
{
printf("Switch Code = %c\n", code );
switch ( code )
      {
case 'A':{
      printf("case a\n");
      return 0.0;
     }
case 'B':{
     printf("case b\n");
     return 1.0;
     }
case 'C':{
      printf("case c\n");
      return 2.0;
     }
case 'D':{
      printf("case d\n");
      return 3.0;
     }
case 'E':{
      printf("case e\n");
      return 4.0;
     }
case 'F':{
      printf("case f\n");
      return 5.0;
    }
case 'G':{
      printf("case g\n");
      return 6.0;
    }
case 'H':{
      printf("case h\n");
      return 7.0;
    }
case 'I':{
     printf("case i\n");
     return 8.0;
   }
case 'J':{
      printf("case j\n");
      return 9.0;
    }
case 'K':{
     printf("case k\n");
     return 10.0;
    }
case 'L':{
      printf("case l\n");
      return 11.0;
    }
default:{
      printf("case default\n");
      return 11.0;
        }

}
}

2 个答案:

答案 0 :(得分:2)

编译器非常明确地说:

1.c:40:25: warning: format specifies type 'int' but the argument has type 'double' [-Wformat]
printf("color1 = %d\n", color1);

切换效果很好,函数Band()可能会返回正确的值,但它们是double,您尝试将它们打印为整数。

printf()格式从%d更改为%f,这样就可以了。

另请注意,color4color5是使用code3计算的,这可能不是意图,而是复制粘贴错误。

答案 1 :(得分:1)

我看到你的函数返回double类型但是在打印时你使用“%d”来进行整数打印。使用%f或%lf(ISO C不支持)打印double类型。对我来说,这是正常的。