繁体   English   中英

While 循环和 do while 循环仅在计算器程序中运行一次。 C++

[英]While loop and do while loop only running once in a calculator program. C++

试图使用 while 循环和内部 class 运行一个简单的计算器。 我的问题是我使用了一个 while 循环,它的条件是当 boolean 调用 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);
    
}

在 C++ 中,布尔值存储为 0 或 1。0 为假,1 为真。 如果您为cin语句输入"true" ,它将不起作用。 您要做的就是将 0 或 1 放入控制台。 您还可以将输入存储为字符串并使用 if 语句来检查它是"true"还是"false" ,并基于此设置 boolean 值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM