我有以下程序:
#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;
}
}
这是一个简单的程序,可根据以下内容根据添加的颜色代码计算欧姆:
例如。输入YVB将给我470欧姆。
我一直在尝试进行反向输出,用户可以在其中输入欧姆并获得颜色输出。例如,如果用户输入470欧姆,他们将得到以下信息:
我在实施此程序时遇到困难,想知道从哪里开始。我尝试将char更改为double并在周围切换值,但这根本不起作用。
另外,是的,我知道我应该使用switch语句而不是其他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 - 对适当色带的抵抗力(Ohms),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36685403/