繁体   English   中英

带char的Switch语句始终在C中返回0

[英]Switch Statement with char always returns 0 in C

由于某种原因,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;
        }

}
}

编译器说的很清楚:

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 ,这可能不是意愿,而是一个复制粘贴错误。

我看到您的函数返回双精度类型,但是在打印时,您使用的是“%d”,它用于整数打印。 使用%f或%lf(ISO C不支持)打印双重字体。 对我来说,它可以正常工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM