【发布时间】:2022-01-16 13:32:52
【问题描述】:
正在尝试使用 while 循环和内部类运行一个简单的计算器。我的问题是我使用了一个 while 循环,它的条件是当一个名为 flag 的布尔值等于 true 时,它会不断地反复运行程序。为了退出 while 循环,我包含了一个部分来询问用户是否要继续并允许他们向标志输入一个值。无论我使用多少不同版本的条件,循环都只运行一次。我目前有一个 do while 循环,它检查一个称为循环的 int 是否小于 2,它被初始化为值为 1。在呈现该值后,它递增 int 循环,使其为 2 并且不满足循环要求。然后询问用户是否要继续,如果为真,则将值重置为 1。仍然没有工作,并且没有在线显示相同的问题或解决方案,即使使用不同的语言也是如此。感谢您的任何补充。
代码:(C++)
// main.cpp
// Calculator
//
// Created by yared yohannes on 12/10/21.
//
class calculation{
public:
calculation(){
}
int add(int first, int second){
int result= first+second;
return result;
}
int minus(int first, int second){
int result= first-second;
return result;
}
int multi(int first, int second){
int result= first*second;
return result;
}
int divide(int first, int second){
int result= first/second;
return result;
}
};
#include <iostream>
using namespace std;
int main(){
int first=0,second=0;
bool flag=true;
char sign;
int loop=1;
calculation calc;
cout<<"Welcome to the calculator program.\n";
do{
cout<<"Please enter the first value: ";
cin>>first;
cout<<"Please enter the desired operation(+,-,*,/): ";
cin>>sign;
cout<<"Please enter the second value: ";
cin>>second;
if(sign=='+'){
cout<<calc.add(first, second)<<"\n";
}
else if(sign=='-'){
cout<<calc.minus(first, second)<<"\n";
}
else if(sign=='*'){
cout<<calc.multi(first, second)<<"\n";
}
else if(sign=='/'){
cout<<calc.divide(first, second)<<"\n";
}
cout<<"Do you want to continue(true or false): ";
cin >> flag;
loop++;
if(flag==true){
loop=1;
}
}while(loop<2);
}
【问题讨论】:
-
不是 100% 匹配,但问题是一样的:cin and boolean input。简而言之,从
cin读取bool只接受0或1作为输入。要读取true或false字符串,您需要std::cin >> std::boolalpha >> flag; -
@Yksisarvinen 我在顶部有“使用命名空间 std”,所以我需要包含 std:: 吗?
-
@Yksisarvinen 很抱歉重复回复。只是在没有 std:: 的情况下尝试过它,它起作用了。非常感谢
-
调试器的功能远不止这些。调试器将向您显示所有变量的值,通过运行程序,一次一行,通过检查每个变量使用的所有变量的值,您可以准确地看到它在做什么以及程序执行每个 if/while 循环的原因if/while 循环你会明白为什么 if/while 循环执行或不执行。
标签: c++ while-loop calculator