【发布时间】:2015-09-29 13:30:36
【问题描述】:
我的目标是使程序尽可能高效。我被这个问题困扰了很长一段时间,当我搜索它时,我被告知flush/endl cout 语句。
当我开始调试时,我推断问题出在for 循环上。它只会跳过for 循环,导致长度、宽度、高度为0。
#include <iostream>
#include <string>
#include <array>
using std::cout; using std::cin;
using std::string; using std::flush;
using std::endl;
void main()
{
int length=0, width=0, height=0, volume=0;
int VolCalcs[3]={length, width, height};
string Prompt[3] = {"Please enter length: ", "Please enter width: ", "Please enter height: "};
string NewResult[3] = {"The new length is ", "The new width is ", "The new height is "};
for(int i=0;i==3;++i)
{
cout<<endl;
cout<<Prompt[i]<<flush;
cin>>VolCalcs[i];
}
volume=length*width*height;
cout<<" The Volume is: "<<volume<<endl;
length++;
width--;
height+=10;
for(int i=0;i==3;++i)
{
cout<<NewResult[i] << VolCalcs[i] <<endl;
}
volume=length*width*height;
cout<<" The New Volume is: "<<volume<<endl<<endl;
cout<<"Press Enter to End Program"<<flush;
cin.ignore();
}
输出如下:
The Volume is: 0
The New Volume is: -10
Press Enter to End Program
【问题讨论】:
-
你的循环条件应该是
i < 3,而不是i == 3。 -
您的代码非常混乱,我担心在这里为您提供各种错误的修复并不能真正帮助您掌握 C++。我建议您从a good book 重新开始。不要再听那些试图向你解释
endl和flush的人了。 -
另外,您将
VolCalcs设置为length, width和height的副本,而不是对它们的引用。所以输入操作不会影响length, width, height。您稍后修改length、width和height的尝试也不会反映在您在第二个循环中输出的VolCalcs中。摆脱单独的length、width和height变量,并在任何地方使用VolCalcs数组。修复循环条件,您应该更接近可行的解决方案。
标签: c++ arrays performance for-loop cout