简体   繁体   English

我想不出让我的代码循环的方法

[英]I cant figure out a way to make my code loop

I am complete starter and i cant figure out how to use the while function in a very simple calucator code.我是一个完整的初学者,我无法弄清楚如何在一个非常简单的计算器代码中使用 while 函数。

ive already tried putting the while function in the code in different ways but nothing of it seems to work it just stop without even giving me the final result of the first "problem"我已经尝试以不同的方式将 while 函数放入代码中,但似乎没有任何效果,它甚至没有给我第一个“问题”的最终结果就停止了

#include "pch.h"
#include <iostream>
using namespace std;

int main()
{

    int number1;
    int number2;
    char op;
    int result;

    cout << "Give first number: ";
    cin >> number1;

    cout << "Give second number: ";
    cin >> number2;

    cout << "Chose operator(+ - / * ): ";
    cin >> op;

    if (op == '+')
    {
        result = number1 + number2;
    }
    else if (op == '-')
    {
        result = number1 - number2;
    }
    else if (op == '*')
    {
        result = number1 * number2;
    }
    else if (op == '/')
    {
        result = number1 / number2;
    }

cout << "The result is: " << result << endl;

system("pause");
return 0;
}

everything its working fine this way i just want it to loop after the first problem and ask again for another one...一切正常,我只是希望它在第一个问题之后循环并再次询问另一个问题......

I am complete starter and i cant figure out how to use the while function in a very simple calucator code.我是一个完整的初学者,我无法弄清楚如何在一个非常简单的计算器代码中使用 while 函数。

Its time for you to get your hands on a good C++ book ...是时候接触一本优秀的 C++ 书籍了……

Syntax of while loop: while (some_condition) { /* Body... */ } while循环的语法: while (some_condition) { /* Body... */ }

Rectified code of above problem:上述问题的更正代码:

#include <iostream>

int main()
{
    int number1, number2, result;
    char op;
    bool is_loop = true;

    while (is_loop) {
        std::cout << "Give first number: ";
        std::cin >> number1;

        std::cout << "Give second number: ";
        std::cin >> number2;

        std::cout << "Chose operator(+ - / * ): ";
        std::cin >> op;

        switch (op)
        {
        case '+':
            result = number1 + number2;
            break;
        case '-':
            result = number1 - number2;
            break;
        case '*':
            result = number1 * number2;
            break;
        case '/':
            result = number1 / number2;
            break;
        default:
            is_loop = false;
        }
        std::cout << "The result is: " << result << std::endl;
        std::cin.get();
    }
    return 0;
}

you may try something like this.. this might be the simplest way of doing this..你可以尝试这样的事情..这可能是最简单的方法..

do{
//your calculator code
char ch;
cout<<"Do you want to continue"<<endl;
cin>>ch;
while(ch=='Y'||ch=='y');

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

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