• 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏吧

如何如果用户输入匹配特定值?

c/c++ 来源:PatrickGamboa 3次浏览

我正在写一个简单的C++测量程序,要求用户输入来选择他们想从哪个单位测量单位和单位?但我不知道结构是否正确(我的C++真的很糟糕)。这里是我的代码:如何如果用户输入匹配特定值?

#include <iostream> 
using namespace std; 

int main() 
{ 
    int storeFROM, storeTO; 
    char mm, cm, m, kk; 

    cout << "Enter the initial unit (mm, cm, m, or km): "; 
    cin >> storeFROM; 

    cout << endl; 

    if ((storeFROM != 'mm') || storeFROM != 'cm' || storeFROM != 'm' || storeFROM != 'km') { 
     cout << "--> Sorry unit to convert FROM is invalid" << endl; 
    } 
    else if ((storeFROM == 'mm') || storeFROM == 'cm' || storeFROM == 'm' || storeFROM == 'km') 
    { 
     cout << "Enter the initial unit(mm, cm, m, or kk) :"; 
     cin >> storeTO; 
    } 

    // Calculate the selected units 
    system("pause"); 
} 

我希望有人能帮助我,要求用户填写他们想哪个单位来问,这正是它应该如何显示:

enter image description here


===========解决方案如下:

下面是正确的代码:

bool isValidUnit(const std::string &unit); 
int convertValue(double value, const std::string &unitFrom, const std::string &unitTo); 

int main() { 

    ... 

    std::string storeFROM, storeTO; 

    cout << "Enter the initial unit (mm, cm, m, or km): "; 
    cin >> storeFROM; 

    if (!isValidUnit(storeFROM)) { 
     cout << "--> Sorry unit to convert FROM is invalid" << endl; 
     ... 
    } 

    cout << "Enter the initial unit (mm, cm, m, or km): "; 
    cin >> storeTO; 

    if (!isValidUnit(storeTO)) { 
     cout << "--> Sorry unit to convert TO is invalid" << endl; 
     ... 
    } 

    double value; 

    cout << "Enter the value in (" << storeFROM << "): "; 
    cin >> value; 

    double valueConverted = convertValue(value, storeFROM, storeTO); 

    cout << "Value in (" << storeTO << "): " << valueConverted << endl; 

    return 0; 
} 

bool isValidUnit(const std::string &unit) { 
    return unit == "mm" || unit == "cm" || unit == "m" || unit == "km"; 
} 

double unitMultiplier(const std::string &unit) { 
    if (unit == "mm") return 0.001; 
    if (unit == "cm") return 0.01; 
    if (unit == "m") return 1; 
    if (unit == "km") return 1000; 
    return 0.; 
} 

double convertValue(double value, const std::string &unitFrom, const std::string &unitTo) { 
    if (unitFrom == unitTo) return value; 
    if (value <= 0.) return 0.; // or value :) 

    // Get it in meters 
    int valueInMetes = value * unitMultiplier(unitFrom); 
    return valuesInMeter/unitMultiplier(unitTo); 
} 

版权声明:本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系管理员进行删除。
喜欢 (0)