如何使用静态投射和家庭作业进行取整

  • 本文关键字:家庭作业 何使用 静态 c++
  • 更新时间 :
  • 英文 :


我已经为学校布置了好几个小时的家庭作业,无法得到正确的输出。我真的不明白这个问题。但这与选角或不正确取整有关。这是一个身高对话分配,单位为厘米到英尺/英寸。看起来很简单,但似乎永远都无法实现。我错过了什么?

  • 此外,您不能使用舍入函数。您只能为练习添加0.5

这是我迄今为止的代码:

// Height conversion assignment from cm to feet and inches

#include <iostream>
using namespace std;

const float CM_TO_INCHES = 2.54;
const int INCHES_TO_FEET = 12;
int main()
{

int cm, inches, feet, inchesRemainder;

cout << "Enter the height in centimeters: ";
cin >> cm;


inches = cm / CM_TO_INCHES;


feet = inches / INCHES_TO_FEET;
inchesRemainder = inches % INCHES_TO_FEET;

cout << cm << " cm(s) = ";


cout << static_cast <int> (feet + 0.5) << " foot (feet) and ";
cout << static_cast <int> (inchesRemainder + 0.5) << " inch(es) " << endl;

return 0;
}

预期输出:

运行1输入高度,单位为厘米--182182厘米=6英尺/英尺和0英寸

运行2以厘米为单位输入高度--165165厘米=5英尺/英尺和5英寸

运行3输入高度,单位为厘米--140140厘米=4英尺/英尺和7英寸

实际输出:

运行1输入高度,单位为厘米--182182厘米=5英尺/英尺和11英寸

运行2以厘米为单位输入高度--165165厘米=5英尺/英尺和4英寸

运行3输入高度,单位为厘米--140140厘米=4英尺/英尺和7英寸

简短的代码回顾:

// Height conversion assignment from cm to feet and inches

#include <iostream>
using namespace std;  // Bad practice; stop using sooner than later
// Prefer double; it's the 'default' floating point type.
// These constants don't need to be global. Get out of that practice
// sooner than later.
const float CM_TO_INCHES = 2.54;  // Names would make more sense as units
const int INCHES_TO_FEET = 12;
int main()
{

int cm, inches, feet, inchesRemainder;  // Prefer declaring variables when needed
// and one at a time.

cout << "Enter the height in centimeters: ";
cin >> cm;

// Currently doing a cast and truncation already.
// Because you're not controlling the process, your results
// are unexpected.
inches = cm / CM_TO_INCHES;  // This is where you need to 'round.'


feet = inches / INCHES_TO_FEET;
inchesRemainder = inches % INCHES_TO_FEET;

cout << cm << " cm(s) = ";  // No need for (s); that's not how units work

// These casts are useless; your variables are already ints
cout << static_cast <int> (feet + 0.5) << " foot (feet) and ";
cout << static_cast <int> (inchesRemainder + 0.5) << " inch(es) " << endl;

return 0;
}

你需要";圆形";并且仅作为初始转换计算的一部分进行强制转换。这实际上只是一个截断,这就是为什么你要加0.5。

int inches = static_cast<int>((cm / CM_PER_INCH) + 0.5);将为您提供正确的英寸数,而您的其他计算可以简单地使用整数。不需要进一步铸造。我的演员阵容中多了一个( ),但我。C++确实遵循了你习惯的算术运算顺序。static_cast<>()也是不需要的,但显式可以向您自己和其他程序员展示您的意图,也就是说,您正在展示需要隐式转换。

我把常数的名称改成了实际单位,因为它就是这样。转换因子,文本等等,都是你和数字一起操作的实际单位。在我的解决方案中,我只使用了典型的x"y";英尺和英寸的符号,因为它更干净,不需要任何分支或双重符号。

最新更新