gpt4 book ai didi

c++ - 简单的c++连续计算器,无法退出程序

转载 作者:行者123 更新时间:2023-11-28 06:58:22 24 4
gpt4 key购买 nike

我用 C++ 制作了这个简单的计算器。它连续接受输入,但我在将我的操作变量定义为 char 时遇到了麻烦,因为它让我无法退出程序。这是代码:

#include <iostream>

int main(){
long double num1, num2; char operation;
std::cout << "Welcome to the calculator!\n\nInput numbers and operations to begin. (2+2) Then hit enter.\n\nThe calculator will continue to expect an operation and number (e.g. +6)\nuntil you enter \"q\" as an operation.\n\nEnter \"q\" as an operation to quit.\n\n";
std::cin >> num1 >> operation >> num2;
do{
switch(operation){
case '+':
num2 += num1;
break;
case '-':
num2 -= num1;
break;
case '/':
num2 /= num1;
break;
case '*':
num2 *= num1;
break;
default:
std::cout << "Not a valid operation. Try again.";
break;
}
std::cout << num2;
} while (std::cin >> operation >> num1);
return 0;
}

程序运行良好,运行良好,只是不知道如何退出。我试过让“q”成为返回 0 的案例,但它似乎不起作用,因为我的 do-while 需要 2 个输入...有什么想法或想法吗?

最佳答案

std::cin >> num1 >> operation >> num2;
do
{
switch(operation){
case '+': num2 += num1; break;
case '-': num2 -= num1; break;
case '/': num2 /= num1; break;
case '*': num2 *= num1; break;
default: std::cout << "Not a valid operation. Try again."; break; }
std::cout << num2;
std::cin >> operation;
if (operation == 'q') break;
else std::cin >> num1;
}
while (1);

示例 I/O3+47+310q结尾3+4

关于c++ - 简单的c++连续计算器,无法退出程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22877030/

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