【问题标题】:Getting output for inches [closed]获取英寸的输出[关闭]
【发布时间】:2023-03-13 00:10:01
【问题描述】:

下面是我编写的用于将用户输入的英寸转换为英里、码、英尺的代码。我唯一的问题是我希望输出的格式也要求输出具有“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;

【问题讨论】:

  • 这个问题真的不清楚。告诉我一件事,你距离用户输入只有几英寸那么你为什么要再次计算它?
  • 这是一个项目,具体输出如下,输入英寸数:12300000 12300000英寸=194英里,226码,2英尺,0英寸。
  • 我可能把事情看得很直白,但我想我会问比我更聪明的人,看看是否有办法让输出镜像。
  • 你的代码没有计算任何接近你想要的输出。想想你是如何手工找出这个答案的,然后在代码中复制那个方法。

标签: c++ unit-conversion


【解决方案1】:

我的猜测是您希望计算级联,例如它需要英寸并将其作用到可能的最大单位。所以 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;
}

【讨论】:

  • 非常感谢!
  • 您可能希望将您的幻数修复为。没有它们只是一个好习惯。
  • 我对编程很陌生,所以不将数字插入源代码是很困难的。我也有一个快速的问题。当我运行上面的代码时,它会按预期打印,但第一行除外。输出显示为:10 英寸 = 71(英里)秒,1302 码,1 英尺,10 英寸。现在剩下的部分有什么我可以改变的吗?如果不是,我可能只是摆弄这个,直到我弄明白为止。再次感谢您的帮助。
  • 是的,我错过了。现在修好了。不能在两个地方都使用 i。
  • static const int INCHES_PER_FOOT = 36; 那是一只大脚……
【解决方案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;

// ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多