不理解为什么代码没有产生所需的答案

Not understanding why code isn't producing desired answer

本文关键字:答案 为什么 代码 不理解      更新时间:2023-10-16

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

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

期望的输出为:树到=2 总空间应为 1.57

实际输出为:树到=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太小而无法满足条件。

相关文章: