gpt4 book ai didi

C++ 提示用户继续或离开

转载 作者:行者123 更新时间:2023-11-28 06:14:49 26 4
gpt4 key购买 nike

实际上,我只是尝试使用 C++ 并在这个特定问题上停下来,而不是关闭程序,它应该询问用户他/她是想继续还是想退出。现在据我了解,我在结尾行中编写了 do-while 代码,但它不起作用。请给我一个解决方案。谢谢!!

#include<iostream>
#include<stdio.h>
#include<cstdlib>
#include<string>

using namespace std;

class Cal
{
public:
int Add(int a, int b)
{
int res;
res=(a+b);
cout << "Answer is " << a << "+" << b << "=" << res << endl;
}
int Sub(int a,int b)
{
int res;
res=(a-b);
cout << "Answer is " << a << "-" << b << "=" << res << endl;
}
int Mul(int a,int b)
{
int res;
res=(a*b);
cout << "Answer is " << a << "*" << b << "=" << res << endl;
}
int Div(int a,int b)
{
int res;
res=(a/b);
cout << "Answer is " << a << "/" << b << "=" << res << endl;
}
};

int main()
{
int first, second, res, operation;

cout<<"**********************************"<<endl;
cout<<"******* Simple Calculator ********"<<endl;
cout<<"**********************************"<<endl;
cout<<"Select the Operation: "<<endl;
cout<<"1. Addition"<<endl;
cout<<"2. Subtraction"<<endl;
cout<<"3. Multiplication"<<endl;
cout<<"4. Divison"<<endl;
cout<<"Choosen Operation is: ";
cin>>operation;
cout << "Enter the 1st Number: ";
cin>>first;
cout << "Enter the 2nd Number: ";
cin>>second;

switch(operation){
case 1:
Cal a;
a.Add(first,second);
break;
case 2:
Cal b;
b.Sub(first,second);
break;
case 3:
Cal c;
c.Mul(first,second);
break;
case 4:
Cal d;
d.Div(first,second);
break;
default:
cout<< "Please Enter a Operation";
break;
}

char ans;
do
{
cout<< "Do you want to continue (Y/N)?\n";
cout<< "You must type a 'Y' or an 'N' :";
cin >> ans;
}
while((ans !='Y')&&(ans !='N')&&(ans !='y')&&(ans !='n'));
}

最佳答案

do while 循环不包含要重复的主体,即计算器部分。

do while 中的条件看起来不正确。

我会试试这个。

int main() {
char ans = 'N';
do {
// calculator stuff, better to be in a separate function

cout << "Do you want to continue (Y/N)?\n";
cout << "You must type a 'Y' or an 'N' :";
cin >> ans;
} while ((ans == 'Y') || (ans == 'y'));
}

关于C++ 提示用户继续或离开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30547478/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com