首页 > 解决方案 > c ++:将用户输入用于控制流以及通过引用函数调用

问题描述

我正在尝试编写一个程序,将用户输入给出的高度转换为用户输入也选择的比例。

首先程序应该询问用户他们想转换成哪个比例,公制或英制。

然后基于该选择,它应该询问用户他们想要转换的高度。

我的问题是我的控制语句似乎不起作用。当我输入“英制”表示我想从公制单位转换为英制单位时,当它应该要求我以公制单位输入时,我被要求输入英制单位的高度,然后它会打印公制高度当它应该返回帝国高度时。

关于如何解决这个问题的任何建议?先感谢您。

#include <iostream>

using namespace std;

void getImperialData(double& big, double& small);

void getMetricData(double& big, double& small);

void toMetric(double& big, double& small);

void toImperial(double& big, double& small);

void giveMetricHeight(double meters, double centimeters);

void giveImperialHeight(double feet, double inches);

int main() {

  double big, small;
  char ans;

  cout << endl << endl;

  do{

    string units;

    cout << "Convert to which units? (metric/imperial): ";
    cin >> units;
    cout << endl << endl;

    if (units == "metric" || "Metric"){

      getImperialData(big, small);
      cout << endl << endl;

      toMetric(big, small);
      cout << endl << endl;

      giveMetricHeight(big, small);
      cout << endl << endl;

    } if (units == "imperial" || units == "Imperial"){

      getMetricData(big, small);
      cout << endl << endl;

      toImperial(big, small);
      cout << endl << endl;

      giveImperialHeight(big, small);
      cout << endl << endl;

    } else {

      cout << "Please choose imperial or metric units.";
      cout << endl << endl;

    }

    cout << "Convert another height? (y/n): ";
    cin >> ans;
    cout << endl;

  }while(ans == 'y' || ans == 'Y');

  return 0;  

}

void getImperialData(double& big, double& small){

  cout << "Enter the number of feet: ";
  cin >> big; 
  cout << endl << endl;

  cout << "Enter the number of inches: ";
  cin >> small;
  cout << endl << endl;

}

void getMetricData(double& big, double& small){

  cout << "Enter the number of meters: ";
  cin >> big; 
  cout << endl << endl;

  cout << "Enter the number of centimeters: ";
  cin >> small;
  cout << endl << endl;

}

void toMetric(double& big, double& small){


  big = 0.3048 * big;
  small = 2.54 * small;

}

void toImperial(double& big, double& small){


  big =  big / 0.3048;
  small = small / 2.54;

}

void giveMetricHeight(double meters, double centimeters){

  cout << "This height is " << meters + centimeters << " meters." << endl << endl;

}

void giveImperialHeight(double feet, double inches){

  cout << "This height is " << feet << " feet " << " and " << inches << " inches." << endl << endl;

}

标签: c++

解决方案


推荐阅读