相当新鲜的编码器正在学习创建一个程序,该程序将从0到99之间的任何给定分输入输出最少的硬币。我不需要为此代码添加任何限制,这就是为什么你看不到任何限制在0到99之间的东西。
这是我所拥有的,但我似乎无法弄清楚如何正确使用模数来保留先前计算中的剩余数字。
我感谢您提供的任何建议!我认为我非常接近,但我的心理墙是%模数。我知道我可以使用长算术计算前一个数字,但我想弄清楚如何用%修饰符缩短它。
#include <iostream>
using namespace std;
int main()
{
int cents;
const int quarter = 25;
const int dime = 10;
const int nickel = 5;
const int penny = 1;
// Get the amount of cents
cout << "Please enter an amount in cents less than a dollar." << endl;
cin >> cents;
// Calculate how many of each coin you can get from cent input
int Q = cents % quarter;
int D = Q % dime;
int N = D % nickel;
int P = N % penny;
// Display the coins you can get from cent input
cout << "Your change will be:" << endl;
cout << "Q: " << Q << endl;
cout << "D: " << D << endl;
cout << "N: " << N << endl;
cout << "P: " << P << endl;
return 0;
}
答案 0 :(得分:1)
%
返回除法的余数,而不是舍入的数字。所以它分配给Q
剩余的分区。我建议您首先计算X
类型硬币的数量,然后将余数传递给下一个计算。像
int Q = cents / quarter;
int D = (cents%quarter) / dime;
等等
答案 1 :(得分:1)
每种硬币类型的总数:
int Q = cents / quarter;
int D = cents / dime;
int N = cents / nickel;
int P = cents / penny;
最少量的硬币
int Q = cents / quarter; cents %= quarter;
int D = cents / dime; cents %= dime;
int N = cents / nickel; cents %= nickel;
int P = cents;
答案 2 :(得分:1)
我不太明白你想要什么,但据我所知,这是我想要你做的事情
int cointypes[4]={25,10,5,1};
int coinnumber[4];
int temp=cents;
for(int i=0;i<=3;i++)
{
coinnumber[i]=temp/cointypes[i];
temp=temp%cointypes[i];
}
cout << "Your change will be:" << endl;
cout << "Q: " << coinnumber[0] << endl;
cout << "D: " <<coinnumber[1] << endl;
cout << "N: " << coinnumber[2]<< endl;
cout << "P: " << coinnumber[3]<< endl;
答案 3 :(得分:1)
以下是使用std::div
和C ++ 17结构化绑定的另一种解决方案:
#include <iostream>
#include <string>
#include <cstdlib>
#include <utility>
#include <vector>
int main()
{
std::vector<std::pair<std::string, int>> coins {
{"quarter", 25},
{"dime", 10},
{"nickel", 5},
{"penny", 1} };
std::cout << "Please enter an amount in cents less than a dollar.\n";
int cents;
std::cin >> cents;
std::cout << "Your change will be:\n";
for(const auto& [coin_name, value] : coins) {
auto[coin_count, remainder] = std::div(cents, value);
cents = remainder;
std::cout << coin_name << "\t: " << coin_count << '\n';
}
}