I am trying to make a calculator for resistor. So the input is a value in Ohms and the output will be the color band of the resistor.
But I've been stuck in this for a while, I'm not sure what is happening. No matter what, the code always go to the default situation.
char a, b, c;
int tolerancia,valor;
printf("enter resistance value: ");
scanf("%i", &valor);
c = valor % 10; // th
b = (valor % 100) / 10; // second digit
a = valor / 100; // first digit
switch (a) //colour band for first digit//
{
case '0':
printf("black ");
break;
case '1':
printf("brown ");
break;
case '2':
printf("red ");
break;
case '3':
printf("orange ");
break;
case '4':
printf("yellow ");
break;
case '5':
printf("green ");
break;
case '6':
printf("blue ");
break;
case '7':
printf("violet ");
break;
case '8':
printf("grey ");
break;
case '9':
printf("white ");
break;
default:
printf("unknown value ");
}
The switch case goes for 3 times (first digit, second digit and tolerance) and in every situation the output is "unknown value"
CodePudding user response:
You're reading an int
, but your switch is comparing the first digit of that int to various characters. Now, char
is a numeric type, so this (kind of) works, but the value of '0'
does not equal 0
and so on for all digit characters.
Thus you go straight to the default case.
More correctly:
switch (a) {
case 0:
printf("black ");
break;
// etc.
}
You could also simply have an array of strings and use the digit to index it. Making sure of course to validate that a
is a valid index.
char *colors[] = {
"black", "brown", "red", "orange", "yellow",
"green", "blue", "violet", "grey", "white"
};
if (a >= 0 && a <= 9) {
printf("%s ", colors[a]);
}
else {
printf("unknown value ");
}