c++ - 了解如何在 C++ 中使用验证循环(帮助)
问题描述
以下是我想要完成的。我的代码在验证循环之外工作。任何帮助将不胜感激!!
重构代码以将所有任务划分为函数。您的变量可以在 main 中声明,也可以在函数中声明为局部变量。根据需要传入参数。不要声明全局变量,除非它是一个常量。
主程序应该包含一个包含至少 4 个项目的菜单,包括“退出”,它调用这些函数(您的任务)并循环直到用户选择退出。应包含一个输入验证循环,以验证用户对其菜单选择的输入。
在函数中,应该至少有一个决策结构,要么是基于 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; }
解决方案
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;
}
推荐阅读
- json - 如果正在使用自定义类型,如何使 Yesod 成为 Key 记录?
- apache-camel - 升级到 3.7.2 后,Apache Camel 中的 FluentProducerTemplate 出现异常
- laravel - Laravel 电报机器人 sdk
- erpnext - 通过自定义脚本更新 frappe 触发字段
- grammar - BNF 语法规范
- android - XMLHttpRequest 未在 react-native Android 中触发/调用任何 [on] 回调
- javascript - 解析错误,我的类型检查器函数上缺少分号
- reactjs - 如何使用动态 url 路由正确管理状态
- node.js - 使用 parse: false in Hapi multipart/form-data 时,流似乎只有 1 个块
- android-studio - Android工作室:无法从gitlab找到包