#include #include #include /* Function to transfer color code from IEC 60062:2016 into an integer. returns 10 on error. Black BK 0 Brown BN 1 Blue BU 6 Gold GD -1 Green GN 5 Gray GY 8 Orange OG 3 Pink PK -3 Red RD 2 Silver SR -2 Violet VT 7 Yellow YE 4 */ int colorCodeToInt(char c1, char c2) { switch(c1) { case 'B': switch (c2) { case 'K': return 0; case 'N': return 1; case 'U': return 6; } break; case 'G': switch (c2) { case 'D': return -1; case 'N': return 5; case 'Y': return 8; } break; case 'O': if (c2 == 'G') { return 3; } break; case 'P': if (c2 == 'K') { return -3; } break; case 'R': if (c2 == 'D') { return 2; } break; case 'S': if (c2 == 'R') { return -2; } break; case 'V': if (c2 == 'T') { return 7; } break; case 'Y': if (c2 == 'E') { return 4; } break; } return 10; } int readBand(bool readSignificant) { char c1, c2, dummy; int band; do { fflush(stdin); // clear keyboard buffer scanf("%c%c", &c1, &c2); band = colorCodeToInt(c1, c2); if (band == 10 || (readSignificant && band < 0)) { printf("This is not a valid color code. Try again: "); } } while (band == 10 || (readSignificant && band < 0)); return band; } // reuse printResistorValue from exercise 5.4 void printResistorValue(double value) { double exponent = log10(value); int base1000exponent = (int) floor(exponent/3); char metricPrefix; value /= pow(10, base1000exponent * 3); switch (base1000exponent) { case -1 : metricPrefix = 'm'; break; case 0 : metricPrefix = ' '; break; case 1 : metricPrefix = 'k'; break; case 2 : metricPrefix = 'M'; break; case 3 : metricPrefix = 'G'; break; } if(value < 10) { printf("%3.1f%c", value, metricPrefix); } else { printf("%3.0f%c", value, metricPrefix); } } bool isE12(int value) { switch(value) { case 10: case 12: case 15: case 18: case 22: case 27: case 33: case 39: case 47: case 56: case 68: case 82: return true; } return false; } int main(void) { char answer, dummy; do { int band1, band2, band3; printf("Enter the first color code: "); band1 = readBand(true); printf("Enter the second color code: "); band2 = readBand(true); printf("Enter the third color code: "); band3 = readBand(false); printf("The value of this resistor is "); int significant = band1*10 + band2; printResistorValue(significant * pow(10, band3)); printf("\n"); if (isE12(significant)) { printf("This value belongs to the E12 series\n"); } else { printf("This value does not belong to the E12 series\n"); } printf("Do you want to continue? "); do { fflush(stdin); // clear keyboard buffer scanf("%c", &answer); if (answer != 'Y' && answer != 'N') { printf("Not a valid answer. Try again (type Y or N): "); } } while (answer != 'Y' && answer != 'N'); } while (answer == 'Y'); return 0; }