如何用算术运算操纵两个参数的结果?

时间:2015-05-13 03:23:57

标签: c++ c++11 calculator

部分解决

检查下面看看我是如何解决这个愚蠢大问题。

我目前正在尝试学习如何将任何数学运算(在控制台中)预先形成前一个数学运算的结果,例如:

user inputs 1
            +
            2
            system("cls");
            3
            *
            2
            system("cls");
            6
            /
            2
            system("cls");
            3

等等。

这是我的代码:

#include <iostream>
#include <string>
#include <windows.h>
using namespace std;

int main()
{
double num,num2, res;
string fchoice;
char choice;


system("cls");
cout << "0\b";
cin >> num;
system("cls");

cout << num << "\n\n";
cout << num << endl;
LOOP:
cin >> choice;
cout << "\n";

switch(choice)
    {
    case '+' :
        cin >> num2;
        res = num + num2 ;
                system("cls");
    cout << res << endl;
        break;

    case '-' :
        cin >> num2;
        res = num - num2 ;
                system("cls");
    cout << res << endl;
        break;
    case '/' :
        cin >> num2;
        res = num / num2 ;
                system("cls");
    cout << res << endl;
        break;
    case '*' :
        cin >> num2;
        res = num * num2 ;
                system("cls");
    cout << res << endl;
        break;
    }



return 0;
}

但问题是,我不知道如何存储最后的结果。 所以我的问题是(如果这对你们来说不是太麻烦):

  • 我如何存储结果,以便我以后可以操作它?
  • 如果用户输入数字而非操作,如何让控制台重置(或删除)以前的结果,并使控制台准备好进行新操作?

    如果你们能给我一些提示,我会感激不尽。

编辑:我忘了提到我是初学者。

最后修改:

我只需添加此行就可以在double num之前重写之前定义的num = res;goto LOOP;,这样它就会始终返回到开头。

1 个答案:

答案 0 :(得分:2)

你真的应该停止使用goto语句并开始使用循环。 (顺便说一句,我可以看到你的标签,但不是你的goto声明?)。要回答第二个问题,您可以在switch语句中添加一个默认语句,如果不是

,它将返回到顶部。
 default:
    goto (any label at beginning of program);

或者,如果您使用的是while循环,只需清除默认语句中的所有值。

作为脚注,为什么要写

cout<<res<<endl;

4次?只需在开关外写一次。