【发布时间】:2020-02-10 01:08:19
【问题描述】:
我正在处理一个显示菜单的任务,并使用 do-while 循环,如果用户输入 4,则函数必须终止。我在哪里搞砸了该功能继续运行? (我已经定义了函数 factorial 和 superfactorial 但它们没有任何内容,因为我还没有完成。
我尝试添加一个 if 语句来确保用户没有选择退出选项
#include <iostream>
#include <cmath>
//Function Prototypes
void ShowMenu();
int getValidUserInputPosNumGT0(int);
int Reverse(int);
int Factorial(int);
int Superfactorial(int);
int validateMenuChoice(int);
int main()
{
int CHOICE, // Holds menu choice
NUM; // User inputted number
const int REVERSE = 1, //Menu choice 1 -> reverse function
FACTORIAL = 2, //Menu choice 2 -> factorial function
SUPERFACTORIAL = 3, //Menu choice 3 -> superfactorial function
QUIT_CHOICE = 4; //Menu choice 4 -> quit program
std::cout << "Welcome to the playing with numbers program!" << std::endl;
do
{
ShowMenu();
std::cin >> CHOICE;
validateMenuChoice(CHOICE);
std::cout << "Enter in a positive number greater than 0: ";
std::cin >> NUM;
getValidUserInputPosNumGT0(NUM);
if (CHOICE !=QUIT_CHOICE)
{
switch (CHOICE)
{
case REVERSE:
Reverse(NUM);
case FACTORIAL:
Factorial(NUM);
case SUPERFACTORIAL:
Superfactorial(NUM);
}
}
}
while (CHOICE !=QUIT_CHOICE);
return 0;
}
int validateMenuChoice (int CHOICE)
{
while (CHOICE < 1 || CHOICE > 4)
{
std::cout << "Please enter a valid menu choice: \n";
std::cin >> CHOICE;
}
}
//Function to display the program menu
void ShowMenu()
{
std::cout << "1) Reverse Number\n"
<< "2) Compute the factorial of a number\n"
<< "3) Compute the superfactorial of a number\n"
<< "4) Quit\n"
<< "Select an option (1-4): ";
}
//Allows a user to enter in an integer and validated that the number is > 0
int getValidUserInputPosNumGT0 (int NUM)
{
while (NUM <= 0)
{
std::cout << "Please enter a positive number greater than 0: ";
std::cin >> NUM;
}
}
//Takes a number as a value parameter and returns the reversed number
int Reverse (int NUM)
{
std::cout << "The Reverse of "<< NUM << " is ";
int reverse = 0, remainder;
while (NUM != 0)
{
remainder = NUM % 10;
reverse = reverse * 10 + remainder;
NUM/=10;
}
std::cout << reverse << std::endl;
}
//takes a number as a value parameter and returns the factorial of the number
int Factorial (int NUM)
{
}
//takes a number as a value parameter and returns the Superfactorial of the number
int Superfactorial (int NUM)
{
}
当用户输入“4”时,程序应该退出/终止,但是,它会继续运行并提示用户输入数字。
【问题讨论】:
-
将
validateMenuChoice和getValidUserInputPosNumGT0从按值调用更改为按引用调用。 -
将
validateMenuChoice(CHOICE);后面的3行移到if内部。 -
你的
switch中也需要breaks。
标签: c++ validation input do-while