1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
|
# include <map>
std::map <std::string, int> const band_value {
{"black" , 0}, {"brown", 1}, {"red" , 2}, {"orange", 3},
{"yellow", 4}, {"green", 5}, {"blue", 6}, {"violet", 7},
{"grey" , 8}, {"white", 9},
};
std::map <std::string, double> const multiplier_value {
{"black" , 1e0}, {"brown", 1e1}, {"red" , 1e2}, {"orange", 1e3},
{"yellow", 1e4}, {"green", 1e5}, {"blue", 1e6}, {"violet", 1e7},
{"grey" , 1e8}, {"white", 1e9}, {"gold", 1e-1}, {"silver", 1e-2}
};
/* Temperature coefficient in parts-per-million per degree celsius. */
std::map <std::string, int> const temp_coeff_value {
{"brown", 100}, {"red" , 50}, {"orange", 15}, {"yellow", 25}
};
/* Resistance tolerance in +/- %. */
std::map <std::string, double> const tolerance_value {
{"brown", 1.0}, {"red" , 2.0}, {"green", 0.5}, {"blue", 0.25},
{"violet", 0.1}, {"grey", 0.05}, {"gold", 5.0}, {"silver", 10.0},
{"none", 20.0}
};
std::vector <std::string> const colors {
"black" , "brown", "red" , "orange", "yellow", "green", "blue",
"violet", "grey" , "white", "silver", "gold"
};
void print_resistor (std::vector <std::string> bands) {
auto compute_ohms = [](auto start_iter, auto end_iter) -> double {
double ohm_result = 0.0;
while (start_iter != end_iter) {
/* Make sure we're not looking at the multiplier band */
if (start_iter != (end_iter - 1)) {
ohm_result *= 10; /* decimal ALSH (e.g., 14 -> 140) */
ohm_result += band_value.at(*start_iter++);
} else { /* Looking at last band. */
return ohm_result * multiplier_value.at(*start_iter);
}
}
return ohm_result;
};
double ohm_result, tolerance, temp_coeff;
ohm_result = tolerance = temp_coeff =
std::numeric_limits<double>::infinity();
try {
switch (bands.size()) {
case 3: {
ohm_result = compute_ohms(bands.begin(), bands.end());
tolerance = tolerance_value.at("none");
} break;
case 4:
case 5: {
ohm_result = compute_ohms(bands.begin(), bands.end() - 1);
tolerance = tolerance_value.at(bands.back());
} break;
case 6: {
ohm_result = compute_ohms(bands.begin(), bands.end() - 2);
tolerance = tolerance_value.at(*(bands.end () - 2));
temp_coeff = temp_coeff_value.at(bands.back());
} break;
default:
std::cerr << "Incorrect number of bands. \n";
std::exit(1);
}
} catch (std::out_of_range const e) {
std::cerr << "Unrecognized band type. Check your resistor!\n";
std::exit(1);
}
std::cout << ohm_result << " ohms at " << tolerance << " percent tolerance";
if (! std::isinf(temp_coeff)) {
std::cout <<", temperature coeff. " << temp_coeff << "\n";
} else std::cout << ".\n";
}
|