首页 > 解决方案 > 了解如何在 C++ 中使用验证循环(帮助)

问题描述

以下是我想要完成的。我的代码在验证循环之外工作。任何帮助将不胜感激!!

  1. 重构代码以将所有任务划分为函数。您的变量可以在 main 中声明,也可以在函数中声明为局部变量。根据需要传入参数。不要声明全局变量,除非它是一个常量。

  2. 主程序应该包含一个包含至少 4 个项目的菜单,包括“退出”,它调用这些函数(您的任务)并循环直到用户选择退出。应包含一个输入验证循环,以验证用户对其菜单选择的输入。

  3. 在函数中,应该至少有一个决策结构,要么是基于 if-then-else 的条件,要么是 switch 语句。

    using namespace std;
    void DecimalToBinary(int n) {
        int binaryNumber[100], num = n;
        int i = 0;
        while (n > 0) {
            binaryNumber[i] = n % 2;
            n = n / 2;
            i++;
        }
        cout << "Binary form of " << num << " is ";
        for (int j = i - 1; j >= 0; j--)
            cout << binaryNumber[j];
        cout << endl;
    }
    int BinaryToDecimal(int n) {
        int decimalNumber = 0;
        int base = 1;
        int temp = n;
        while (temp) {
            int lastDigit = temp % 10;
            temp = temp / 10;
            decimalNumber += lastDigit * base;
            base = base * 2;
        }
        cout << "Decimal form of " << n << " is " << decimalNumber << endl;;
    }
    int main() {
        DecimalToBinary();
        BinaryToDecimal(10101);
    
        int choice;
        int input;
    
    do {
        cout << "Enter 1 to exit the program: \n";
        cout << "Enter 2 to enter a binary number: \n";
        cout << "Enter 3 to enter a decimal number: \n";
        cout << "Enter 4 to do something else: \n";
        cin >> input;
        switch (input) {
        case '1':
            choice = 1;
            break;
        case '2':
            choice = 1;
            break;
        case '3':
            choice = 1;
            break;
        case '4':
            choice = 1;
            break;
        default:
            choice = 0;
        }
    
    } while (choice);
    
    DecimalToBinary();
    BinaryToDecimal(10101);
    return 0;
    }
    

标签: c++loopsvalidation

解决方案


int main() {

    int choice;
    int input;

do {
    cout << "Enter 1 to exit the program: \n";
    cout << "Enter 2 to enter a binary number: \n";
    cout << "Enter 3 to enter a decimal number: \n";
    cout << "Enter 4 to do something else: \n";
    cin >> input;
    switch (input) {
    case 1:
        choice = 0;
        break;
    case 2:
        int number;
        cout<<"Enter a binary number: ";
        cin>>number;
        cout<<endl;
        BinaryToDecimal(number);
        break;
    case 3:
        int decimalNumber;
        cout<<"Enter a decimal number:";
        cin>>decimalNumber;
        cout<<endl;
        DecimalToBinary(decimalNumber);
    case 4:
        choice = 1;
        break;
    default:
        choice = 0;
    }

} while (choice);

return 0;
}

推荐阅读