我用c ++做了一个有点非正统的计算器,如何让它变得更好

I made a bit unorthodox calculator in c++, how to make it better?

本文关键字:计算器 非正统 变得更好 一个 我用      更新时间:2023-10-16

我用 name: 和 goto name 等在 C++ 中制作了一个计算器,我读到这是不可取的。我应该怎么做,为什么不好?关于我如何改进我的代码的一些提示也会很好,因为我对你选择算术表达式的方式并不完全满意。

Code:
    #include <iostream>

using namespace std;

int main()
{
                    double nr1, nr2, sum;
                    int tegn, y, res1;
        nr1=0;
        nr2=0;
        tegn=0;
        sum=0;
        res1=0;
        y=1;
restart:
cout<<"Enter a number for your preferred arithmetic expression."<<endl<<"Press 1 for addition"<<endl;
cout<<"Press 2 for subtraction"<<endl<<"Press 3 for division"<<endl<<"Press 4 for multiplication"<<endl;
cin>>tegn;
switch(tegn)
{
case 1:
    goto addition;
break;
case 2:
    goto subtraction;
break;
case 3:
    goto division;
break;
case 4:
    goto multiplication;
break;
default:
    cout<<"Wrong button pressed, restarting"<<endl;
    goto restart;
    break;
}
addition:
cout<<"Enter your first number, please"<<endl;
cin>>nr1;
cout<<"Now, enter you second number, please"<<endl<<endl;
cin>>nr2;
    sum=nr1+nr2;
cout<<nr1<<" + "<<nr2<<" = "<<sum<<endl;
cout<<"Enter y(yes) or n(no) to restart"<<endl;
cin>>res1;
    if (res1==y) {
        goto restart;
    }
    else {
        goto end;
    }
subtraction:
    cout<<"Enter your first number, please"<<endl;
cin>>nr1;
cout<<"Now, enter you second number, please"<<endl<<endl;
cin>>nr2;
    sum=nr1-nr2;
cout<<nr1<<" - "<<nr2<<" = "<<sum<<endl;
cout<<"Enter y(yes) or n(no) to restart"<<endl;
cin>>res1;
    if (res1==y) {
        goto restart;
    }
    else {
        goto end;
    }
division:
    cout<<"Enter your first number, please"<<endl;
cin>>nr1;
cout<<"Now, enter you second number, please"<<endl<<endl;
cin>>nr2;
    sum=nr1/nr2;
cout<<nr1<<" :"<<nr2<<" = "<<sum<<endl;
cout<<"Enter y(yes) or n(no) to restart"<<endl;
cin>>res1;
    if (res1==y) {
        goto restart;
    }
    else {
        goto end;
    }
multiplication:
    cout<<"Enter your first number, please"<<endl;
cin>>nr1;
cout<<"Now, enter you second number, please"<<endl<<endl;
cin>>nr2;
    sum=nr1*nr2;
cout<<nr1<<" * "<<nr2<<" = "<<sum<<endl;
cout<<"Enter y(yes) or n(no) to restart"<<endl;
cin>>res1;
    if (res1==y) {
        goto restart;
    }
    else {
        goto end;
    }
end:
    return 0;
}

被称为非结构化编程。 老实说,在这种规模下它很好,但是经过一段时间后它非常"只写",并且随着程序变大而变得繁琐。

结构化编程涉及循环、子过程和函数。 面向对象编程涉及创建抽象概念和通信协议的新对象。 基于事件是另一个,一元、函数、协程状态机等也是如此。

但是,通常之后的下一步是学习如何编写函数或子过程。 你获取一些代码,定义输入和输出,并将其放入函数中。 通常,您可以清除执行此操作的每个goto。 创建一个调度到帮助程序函数的中心循环。 仔细定义循环之间持续存在的状态。

这需要练习。 祝你好运。