'Why am I receiving wrong values (resistor color code calculator)
I want to make a resistor color code calculator but it seems it doesn't work properly. Most combinations seem to return accurate values but whenever I try using gold and silver multipliers, the code returns 0.00. Since gold is 10^-1; shouldn't the code return 22*10^-2 which is 0.22? How can I fix this issue?
typedef enum Color {
SILVER = -2 ,
GOLD = -1 ,
BLACK = 0,
BROWN,
RED,
ORANGE,
YELLOW,
GREEN,
BLUE,
VIOLET,
GREY,
WHITE
} Color;
typedef struct Resistor {
Color ring1;
Color ring2;
Color multiplier;
} Resistor ;
double resistor_calculate_value(Resistor self) {
return (self.ring1 * 10 + self.ring2) * (unsigned int) pow(10, self.multiplier);
}
int main() {
Resistor res1;
res1.ring1 = RED;
res1.ring2 = RED;
res1.multiplier = GOLD;
printf("%f\n", resistor_calculate_value(res1));
return 0;
}
Solution 1:[1]
Don't cast the result of pow() to unsigned int if you want the result to be floating point. Removing the cast gives result 2.2, that is: 22 * 10^-1.
It's generally a very bad idea to mix fixed point and floating point calculations in the same expression. You should ensure that all operands are floating point.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Lundin |
