0

下面是我编写的用于将用户输入的英寸转换为英里、码、英尺的代码。我唯一的问题是我希望输出的格式也需要输出具有“0英寸”。

对于我的生活,我无法弄清楚那么多。我尝试将一个新的 int 值设置为英寸并让它返回 0,但这只会让事情变得更加混乱。

谢谢你的帮助。

#include <iostream>
using namespace std;

int
main ()
{


  double m;
  double y;
  double f;
  double i;

  cout << " Enter the Length in inches:";
  cin >> i;

  m = i / 63360;        // Convert To Miles
  y = 1760 * m;         // Convert To Yards
  f = 3 * y;            // Convert to Feet
  i = 12 * f;           // Convert to Inches

  cout << i << "inches =" << " " << m << " " << "(mile)s," << " " <<
  y << " " << "yards," << " " << f << " " << "feet," << " " << i <<
    " " << "inches." << endl;



  return 0;
4

2 回答 2

2

这可能更接近您想要的:

// ...

int m;
int y;
int f;
int i;
int len;

cout << " Enter the Length in inches:";
cin >> len;

cout << len << "inches = ";

m = len / 63360;        // Miles
len -= m * 63360;
y = len / 36;           // Yards
len -= y * 36;
f = len / 12;           // Feet
i = len % 12;           // Inches

if (m)
    cout << m << " (mile)s, ";
if (y)
    cout << y << " yards, "; 
if (f)
    cout << f << " feet, ";

cout << i << " inches." << endl;

// ...
于 2017-07-21T19:47:46.930 回答
0

我的猜测是您希望计算级联,例如它需要英寸并将其作用到可能的最大单位。所以 15" 会变成 1' 3"。如果我的猜测是错误的,请忽略这个答案。

#include <iostream>
using namespace std;

static const int INCHES_PER_MILE =  63360;
static const int INCHES_PER_YARD =  36;
static const int INCHES_PER_FOOT =  12;

int main ()
{
     int inches, m, y, f ,i, remainder; //int so that we dont get decimal values

     cout << " Enter the Length in inches:";
     cin >> inches;

     m = inches / INCHES_PER_MILE ;             // Convert To Miles  -- shouldn't be 'magic numbers'
     remainder= inches % INCHES_PER_MILE ;      // % stands for modulo -- (i.e. take the remainder)
     y = remainder / INCHES_PER_YARD;        // Convert To Yards
     remainder = remainder % INCHES_PER_YARD;
     f = remainder / INCHES_PER_FOOT;        // Convert to Feet
     remainder = remainder % INCHES_PER_FOOT;
     i = remainder;             // Convert to Inches

     cout << inches << " inches = " << m <<" (mile)s, " <<
     y << " yards, " << f << " feet, " << i << " inches." << endl;

     return 0;
}
于 2017-07-21T19:44:25.320 回答