有没有办法缩短这个项目
Is there a way to shorten this project?
我写了一个计算三角形面积的项目。这个程序是我写的。
#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;
}
与其每次都写cin
和cout
,有没有办法缩短这个项目并缩短它。也许就像把cout
和cin
写在一行里一样?或者其他任何东西,只是为了让它看起来更干净、更漂亮。
看起来很乱。
谢谢!
这需要减少整整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;
}
就像你想把cout
和cin
写在一行中一样,你可以这样写,但我认为这样写并不"干净",最好去掉一行。
而且,请不要使用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
此外,您可能需要进行检查,以确保用户已使用此功能输入了一个号码。
相关文章:
- 有符号的int和int-有没有一种方法可以在C++中区分它们
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- 有没有办法将谓词中的元素偏移量传递给 std 算法?
- 有没有一种方法可以创建一个带有哈希表的数据库,该哈希表具有恒定时间查找功能
- 遇到新行时,有没有办法停止istream_iterator
- 有没有一种方法可以在编译时获得作用域类名
- 有没有办法使用输入的维度初始化 2d 数组中的所有项目而不循环C++?
- 有没有办法缩短这个项目
- 有没有一种简单的方法可以在C++中获取特定索引之后向量中的所有项目?
- 有没有更好的方法来检测向量中一个项目的多次出现?
- 有没有像NPM这样的C++项目经理
- 有没有办法在整个项目中包含和链接外部库,只编辑我的顶级 CMakeList
- 有没有办法将文件包含在C++中的所有项目文件中
- 有没有办法设置 Eclipse 以使用另一个项目的输出作为库?
- 有没有一种简单的方法可以将多个资源添加到 Win32/C++ 项目
- 有没有一种方法可以在不重建任何项目的情况下重新链接解决方案
- 有没有QPair类,但针对三个+项目而不是两个
- 有没有办法在同一项目中的另一个.cpp中使用.cpp中声明的静态空隙
- 有没有办法在Visual Studio Express '12项目中编译和运行单个.cpp文件?
- Very Quick global .h Question(有了它,有些项目仍然没有定义)