如何解决c ++使用数组和指针获取数字的总和
因此,我正在做一个程序,需要查找所有楼层的总面积,这些楼层由用户确定。我认为我使用指针是正确的,因此要检查代码是否正确,我尝试使用基本加法进行操作。但是即使进行基本添加,它似乎也已经存在一些问题。我尝试在这里寻找类似的问题,但找不到任何可能对我有帮助的东西,所以希望你们能帮助我。预先谢谢你。
float *Length=NULL,*Width=NULL,*Area=NULL,TotalArea,templ,tempw;
int floors,count;
cout << "Input the number of floors to proceed\n";
cout << ":";
cin >> floors;
Length = new float[floors];
Width = new float[floors];
Area = new float[floors];
for (int loop = 0; loop < floors; loop++)
{
cout << "\n\nFloor " << loop + 1 << endl;
cout << "Input the Length: \n";
cin >> templ;
cout << "Input the Width: \n";
cin >> tempw;
*(Length + loop) = templ;
*(Width + loop) = tempw;
*(Area + loop) = (*Length + loop) + (*Width + loop);
count = loop;
for (int count = 0; count < floors; count++)
{
TotalArea = TotalArea + *Area+count;
}
}
cout << TotalArea << endl;
我尝试输入以下内容: 楼层:2
1楼 长度:1 宽度:1 2楼 长度:1 宽度:1
答案应该为4,但输出最终为10。
解决方法
您不需要数组和指针。由于您正在遍历楼层并汇总每个楼层的面积,因此您可以“忘记”以前遇到的长度,宽度和面积,而只记得到目前为止遇到的总面积。
float length;
float width;
float area;
float totalArea;
int floors;
std::cout << "Input the number of floors to proceed\n";
std::cout << ":";
std::cin >> floors;
totalArea = 0;
for (int loop = 0; loop < floors; loop++)
{
std::cout << "\n\nFloor " << loop + 1 << std::endl;
std::cout << "Input the Length: " << std::endl;
std::cin >> length;
std::cout << "Input the Width: " << std::endl;
std::cin >> width;
area = length * width;
totalArea += area;
}
std::cout << totalArea << std::endl;
注意我如何在所有地方添加这些烦人的std::
吗?如果您想知道为什么,请参见以下其他问题:Why is “using namespace std;” considered bad practice?
我尝试根据你们的评论进行一些更改,这就是我所做的。 有些警告我我真的不知道为什么,但是似乎有效
float* Length = NULL,* Width = NULL,TotalArea,tempw,templ,* Area = NULL;
int floors,loop = 0;
cout << "Input the number of floors to proceed\n";
cout << ":";
cin >> floors;
for (int loop = 0; loop < floors; loop++)
{
Length = new float[floors];
Width = new float[floors];
Area = new float[floors];
cout << "\n\nFloor " << loop + 1 << endl;
cout << "Input the Length: \n";
cin >> templ;
cout << "Input the Width: \n";
cin >> tempw;
*(Length +loop) = l;
*(Width+loop) = w;
Area[floors] = (*(Length+loop)) * (*(Width+loop));
TotalArea += a[floors];
}
cout << TotalArea << endl;
这是我随身带的东西,它似乎正在工作,现在输出也正确。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。