gpt4 book ai didi

c++ - 不明白为什么代码没有产生所需的答案

转载 作者:行者123 更新时间:2023-12-01 22:35:01 25 4
gpt4 key购买 nike

我接到的作业是要求我找出一定长度内可以放置多少棵树,以及它们将占用多少总空间,包括树之间所需的空间。感谢一些帮助,我已经能够获得正确的树总数,但占用的总空间不正确。我可以做什么来解决这个问题。

输入为:长度 = 10,TRAradius = .5,ReqSpace = 3

期望的输出是:TreeTot = 2总空间应为 1.57

实际输出为:TreeTot = 2 总空间为 6.1

这是我正在使用的代码。

#include <iostream> 
#include <iomanip>

using namespace std;

const double PI = 3.14;

int main()
{
double length;
double TRadius;
double ReqSpace;
int TreeTot = 0;

cout << "enter length of yard: ";
cin >> length;
cout << "enter radius of a fully grown tree: ";
cin >> TRadius;
cout << "required space between fully grown trees: ";
cin >> ReqSpace;

while (length > TRadius * 2 + ReqSpace) {
TreeTot += 1;
length -= (TRadius * 2) + ReqSpace;
}
cout << "The total space taken up is ";
cout << setprecision(2) << TreeTot * TRadius * PI + ReqSpace << endl;
cout << "The total amount of trees is ";
cout << TreeTot;


return 0;
}

最佳答案

这两行:

        TreeTot + 1;
length - (TRadius * 2) + ReqSpace;

是有效的语句,但它们只是表达式。您计算一个值,但不对它执行任何操作。 TreeTot + 1...然后呢?您需要将计算出的值分配给某些东西。大概您想要增加 TreeTot 并减少 length。只需像这样分配值:

        TreeTot = TreeTot + 1;
length = length - (TRadius * 2) + ReqSpace;

或者使用简写来修改结果并将结果分配给相同的值:

        TreeTot += 1;
length -= (TRadius * 2) + ReqSpace;

你的答案可能仍然是错误的,因为 if 语句只运行一次 - 你永远不会告诉它你希望它多次执行代码。如果将 if 更改为 while,则代码将循环,直到 length 太小而无法满足条件。

关于c++ - 不明白为什么代码没有产生所需的答案,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59994308/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com