有没有办法缩短这个项目

Is there a way to shorten this project?

本文关键字:项目 有没有      更新时间:2023-10-16

我写了一个计算三角形面积的项目。这个程序是我写的。

#include <iostream>
using namespace std;
int main()
{
int first, two, three;
int all = (first + two) * three;
cout << "Enter first num: ";
cin >> first;
cout << "nEnter second num: ";
cin >> two;
cout << "nEnter num three: ";
cin >> three;
cout << "You have choosed to do: (" << first << " + " << two << ") * " << three;
cout << "nnThis is equal to: " << all;
return 0;
}

与其每次都写cincout,有没有办法缩短这个项目并缩短它。也许就像把coutcin写在一行里一样?或者其他任何东西,只是为了让它看起来更干净、更漂亮。

看起来很乱。

谢谢!

这需要减少整整1行。它是更干净还是更容易理解取决于你。。。。

int sides[3];
for (int i=0; i < 3; i++)
{
cout << "Enter side " << i+1 << endl;
cin >> sides[i];
}

编写简短的代码会让代码更清晰,这很好,所以一定要不断考虑如何做到这一点。让它看起来漂亮也是一个值得考虑的问题——同样,只要它能让你做的事情更清楚。

清晰就是一切!!

如果你真的想缩短你的项目,让它更"干净",你可以这样做。

#include <iostream>
int main()
{
std::string str = "string"; std::cin >> str;
return 0;
}

就像你想把coutcin写在一行中一样,你可以这样写,但我认为这样写并不"干净",最好去掉一行。

而且,请不要使用using namespace std;——这是一种糟糕的做法。

为了使代码更易于维护和可读:

1( 使用更有意义的变量名称,或者如果要连续命名,请使用数组

例如int numbers[3]

2( 类似地,当你接受这样的提示时,考虑将提示放在问题的平行数组中,或者如果它们是相同的提示,则使用类似于noelicus答案的东西。

我会这样做:

int numbers[3];
String prompts[3] = {"put your", "prompts", "here"};
for(int i=0; i<3; i++){
cout << prompts[i] << endl;
cin >> numbers[i]
}
//do math
//print output

此外,您可能需要进行检查,以确保用户已使用此功能输入了一个号码。

相关文章: