我写了这个小程序来计算变化。只是想问一下是否有一种方法可以重构它或以更简单/更好的方式编写它?我是编程新手,这是Udemy提出的代码挑战。
尝试从每个挑战中尽最大努力。
#include <iostream>
using namespace std;
int main() {
const int dollars {100};
const int quarters {25};
const int dimes {10};
const int nickles {5};
const int penny {1};
int ch_dollars{0}, ch_quarters{0}, ch_dimes{0}, ch_nickles{0}, ch_penny{0}, change{0}, user_input{0};
cout << "Please enter the amount in cents: ";
cin >> user_input;
cout << endl;
change = user_input;
ch_dollars = (change - (change % dollars)) / dollars;
change %= dollars;
ch_quarters = (change - (change % quarters)) / quarters;
change %= quarters;
ch_dimes = (change - (change % dimes)) / dimes;
change %= dimes;
ch_nickles = (change - (change % nickles)) / nickles;
change %= nickles;
ch_penny = (change - (change % penny)) / penny;
cout << "You entered " << user_input << ", your change is: " << endl;
cout << "Dollars: " << ch_dollars << endl;
cout << "Quarters: " << ch_quarters << endl;
cout << "Dimes: " << ch_dimes << endl;
cout << "Nickles: " << ch_nickles << endl;
cout << "Pennies: " << ch_penny << endl;
return 0;
}
最佳答案
ch_dollars = change / dollars;
change %= dollars;
ch_quarters = change / quarters;
change %= quarters;
ch_dimes = change / dimes;
change %= dimes;
ch_nickles = change / nickles;
change %= nickles;
ch_penny = change;
关于c++ - 改进我的代码以应对C++挑战,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55814891/