我有以下程序:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
void print_codes( void ); /* menu of codes */
double decode_char( char code );
main() {
char code1, code2, code3; /* one code per band */
double resistance;
double color1, color2, color3; /* decoded values */
/* Print codes and prompt for user input. */
print_codes();
printf( "\n\n\tEnter three codes. " );
/* Read three character codes. */
code1 = getchar();
code2 = getchar();
code3 = getchar();
/* Decode each character code. */
color1 = decode_char( code1 );
color2 = decode_char( code2 );
color3 = decode_char( code3 );
/* Check whether codes were legal. */
if ( color1 == -999.0 || color2 == -999.0 || color3 == -999.0 )
printf( "\n\n\tBad code -- cannot compute resistance\n" );
/* If codes were legal, compute and print resistance in ohms. */
else {
resistance = ( 10.0 * color1 + color2 ) * pow( 10.0, color3 );
printf( "\n\n\tResistance in ohms:\t%f\n", resistance );
}
return;
}
/* This function prints a menu of color codes to guide the user in
entering input. */
void print_codes( void ) {
printf( "\n\n\tThe colored bands are coded as follows:\n\n\n\t" );
printf( "COLOR\t\t\tCODE\n\t" );
printf( "-----\t\t\t----\n\n" );
printf( "\tBlack-------------------> B\n" );
printf( "\tBrown-------------------> N\n" );
printf( "\tRed---------------------> R\n" );
printf( "\tOrange------------------> O\n" );
printf( "\tYellow------------------> Y\n" );
printf( "\tGreen-------------------> G\n" );
printf( "\tBlue--------------------> E\n" );
printf( "\tViolet------------------> V\n" );
printf( "\tGray--------------------> A\n" );
printf( "\tWhite-------------------> W\n" );
}
double decode_char( char code ) {
if (code == 0.0) {
return 'B';
}
else if (code == 1.0) {
return 'N';
}
else if (code == 'R') {
return 2.0;
}
else if (code == 'O') {
return 3.0;
}
else if (code == 'Y') {
return 4.0;
}
else if (code == 'G') {
return 5.0;
}
else if (code == 'E') {
return 6.0;
}
else if (code == 'V') {
return 7.0;
}
else if (code == 'A') {
return 8.0;
}
else if (code == 'W') {
return 9.0;
}
else {
return -990.0;
}
}
这是一个简单的程序,可以根据添加的颜色代码来计算欧姆:
E.G.输入 YVB 会给我 470 欧姆。
我一直在尝试进行反向输出,用户可以输入欧姆并获得颜色输出。例如,如果用户输入 470 欧姆,他们将得到:
我在实现此操作时遇到困难,想知道从哪里开始。我尝试将 char 更改为 double 并切换值,但这根本不起作用。 另外,是的,我知道我应该使用 switch 语句而不是 else if 语句,但这现在不是我的问题。
最佳答案
您可以使用 mod 运算符 %
来查找数字并将其与颜色相匹配。然后在每一步之后将 ohm
除以 10,以获得下一个数字。例如:
int ohm = 470;
char map[11] = "BNROYGEVAW";
char color[10];
for (int i = 0; i < 10; i++)
color[i] = 0;
for (int i = 0; i < 10; i++)
{
int n = ohm % 10;
color[i] = map[n];
ohm /= 10;
if (ohm == 0)
break;
}
for (int i = 9; i >= 0; i--)
if (color[i])
printf("%c", color[i]);
关于c - 对适当色带的电阻(欧姆),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36685403/