Som*_*g17 -1 c++ algorithm math
我正在尝试编写一个程序,该程序将返回特定整数美分的零钱。例如 92 美分将返回:0 美元、3 个 25 美分、1 毛钱、1 镍币和 2 便士。
这是我到目前为止的代码:
#include <iostream>
using namespace std;
int main() {
// 1. ask user to enter an integer: total cents
cout << "Hi! Enter an integer representing the total number of cents pls: " << endl;
int user_num{};
// 2. save in std cin
cin >> user_num;
// 3. check dollars
int dollars{};
int add_to_dollars{};
if ( user_num >= 100 ) { // eg. user_num is 240
// calculate amount to add to dollars variable
add_to_dollars = user_num / 100; // 240 / 100 = 2.4 keep the 2
dollars = dollars + add_to_dollars;
// what is the total user_num once we subtract the dollars? eg. 240 - 200 = 40
user_num = user_num % 100; // 240 % 100 = 40
}
// 4. check quarters
int quarters{};
int add_to_quarters{};
if ( user_num >= 25 ) { // eg. 40
// how much do we add to quarters variable?
add_to_quarters = user_numd/25; // 40 / 25 = 1.6
quarters = quarters + add_to_quarters; // add the 1 ^
// subtract this to total cents eg. subtract 25
user_num = user_num % 25;
}
// 5. check dimes
int dimes{};
int add_to_dimes{};
if ( user_num >= 10 ) {
add_to_dimes = user_num / 10;
quarters = quarters + add_to_dimes;
user_num = user_num % 10;
}
// 6. check nickels
int nickels{};
int add_to_nickels{};
if ( user_num >= 5 ) {
add_to_nickels = user_num / 5;
quarters = quarters + add_to_nickels;
user_num = user_num % 5;
}
// 7. check pennies
int pennies{};
int add_to_pennies{};
if ( user_num >= 1 ) {
add_to_pennies = user_num / 1;
quarters = quarters + add_to_pennies;
user_num = user_num % 1;
}
// 8. return total info of each variable
cout << "You can provide change for this change as follows: " << endl;
cout << "dollars: " << dollars << endl;
cout << "quarters: " << quarters << endl;
cout << "dimes: " << dimes << endl;
cout << "nickels: " << nickels << endl;
cout << "pennies: " << pennies << endl;
cout << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
然而,例如,92 美分的答案给了我 7 个 25 美分,而实际上应该是 3 个 25 美分。我是否错误地编写了 C++ 代码,逻辑本质上是错误的吗?提前致谢!
问题是您有一些复制粘贴错误:
quarters = quarters + add_to_dimes;
// ...
quarters = quarters + add_to_nickels;
// ...
quarters = quarters + add_to_pennies;
Run Code Online (Sandbox Code Playgroud)
这些应该分别使用dimes、nickels和pennies来代替quarters。
为了防止将来出现此类错误,如果您发现自己复制粘贴代码,请考虑将该代码重构为函数。例如,在这种情况下,您可以有一个函数,例如int calculate_partial_change(int total_cents, int coin_denomination)一次处理一种类型的硬币。