我是C ++初学者。我刚刚制作了一个硬币找零计算器,现在我想使代码更短(带有循环等)。我怎样才能做到这一点?
#include <iostream>
int main() {
int amount = 0;
int result[4] = { 0, 0, 0, 0 };
int values[4] = { 25, 10, 5, 1 };
int x = 0;
std::cout << "Welcome to this super advanced (not) coin change calculator! \n";
std::cout << "Please enter the amount in cents: ";
std::cin >> amount;
x = amount;
result[0] = x / values[0];
x = x % values[0];
result[1] = x / values[1];
x = x % values[1];
result[2] = x / values[2];
x = x % values[2];
result[3] = x / values[3];
x = x % values[3];
std::cout << "Optimal change: " << result[0] << " quarter(s), " << result[1] << " dime(s), " << result[2] << " nickel(s), and " << result[3] << " pennie(s)!";
return 0;
}
答案 0 :(得分:0)
一些技术适用
1)不是将多个字符串文字输出到std::cout
,而是将所有文字合并为一个,然后输出。请记住,一对紧随其后的字符串文字是结合在一起的。例如,构造"ab" "cd"
变为"abcd"
2)消除所有不需要的变量。就您而言,您读过amount
,分配了x = amount
,然后再也不使用amount
。这意味着有机会消除amount
(直接读到x
并从那里继续)或x
(不要分配x = amount
,然后进行所有操作)在amount
上。
3)如果您正在重用仅由一个索引(例如result[0] = x/values[0]
和后来的result[1] = x/values[1]
)所不同的逻辑,那么请考虑循环。
4)如果您要输出多个字符串(可以!),请考虑将它们也放置在数组中-如果循环也访问该数组的元素。
5)如果可以合理化,不要害怕将语句分解成碎片并重新排序操作。
6)如果我们正在做x = x op y
,请将其更改为x op = y
。例如,将amount = amount % values[i]
更改为amount %= values[i]
。
将所有内容放在一起,就可以得到。
#include <iostream>
int main()
{
int amount = 0;
int result[4] = { 0, 0, 0, 0 };
int values[4] = { 25, 10, 5, 1 };
const char *denom[4] = {"quarter(s),",
"dime(s),",
"nickel(s), and",
"pennie(s)!"
};
std::cout << "Welcome to this super advanced (not) coin change calculator!\n"
"Please enter the amount in cents: ";
std::cin >> amount;
for (i = 0; i < 4; ++i)
{
result[i] = amount / values[i];
amount %= values[i];
}
std::cout << "Optimal change: ";
for (i = 0; i < 4; ++i)
{
std::cout << result[i] << denom[i] << " ";
}
return 0;
}
但是我们可以走得更远。在上面,为清楚起见,我将denom
的初始化分成了多行,但是它们可以在一行中完成,但是可以将它们合并为一行(但要花一些可读性)
const char *denom[4] = {"quarter(s),", "dime(s),", "nickel(s), and", "pennie(s)!"};
完成此操作后,我们看到,如果我们移动两个循环之间的输出语句,并且实际上不需要数组result
(元素仅在循环中计算,并且然后输出)。因此,我们可以消除该数组,并使其成为单个变量-局部于循环。
std::cout << "Optimal change: ";
for (int i = 0; i < 4; ++i)
{
int result = amount / values[i];
amount %= values[i];
std::cout << result << denom[i] << " ";
}
return 0;
}
已完成此操作,请在循环内部查看,请注意,result
仅是计算得出的,因此我们可以将其输出。因此,通过将循环更改为
for (int i = 0; i < 4; ++i)
{
std::cout << amount/values[i] << denom[i] << " ";
amount %= values[i];
}
做了所有这些,我们得到了
#include <iostream>
int main()
{
int amount = 0;
int values[4] = { 25, 10, 5, 1 };
const char *denom[4] = {"quarter(s),", "dime(s),", "nickel(s), and", "pennie(s)!"};
std::cout << "Welcome to this super advanced (not) coin change calculator!\n"
"Please enter the amount in cents: ";
std::cin >> amount;
std::cout << "Optimal change: ";
for (int i = 0; i < 4; ++i)
{
std::cout << amount/values[i] << denom[i] << " ";
amount %= values[i];
}
return 0;
}
在执行上述操作时,我专注于简化您的代码。我已经自由更改了操作顺序,但是产生的输出将是相同的。