我用c ++做了一个有点非正统的计算器,如何让它变得更好
I made a bit unorthodox calculator in c++, how to make it better?
我用 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。 创建一个调度到帮助程序函数的中心循环。 仔细定义循环之间持续存在的状态。
这需要练习。 祝你好运。
相关文章:
- 如何确定我已使用非编码文件到达 EOF?
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 将公共但非静态的成员函数与ALGLIB集成
- 不同翻译单元中不可重载的非内联函数定义
- 不能在初始值设定项列表中将非常量表达式从类型 'int' 缩小到'unsigned long long'
- 初始化具有非默认构造函数的std::数组项的更好方法
- constexpr 函数中的非文字(通过 std::is_constant_evaluated)
- 如何在C++中使用非静态成员函数作为回调函数
- 数组中最大的非重复元素
- QML:修改在不同QML文件(而非main.QML)中定义的子对象的属性
- 有没有可能有一个只有ADL才能找到的非好友功能
- 为x86而非x64编译时出错
- 有没有办法从非C/C++文件中读取C++原始字符串文字的内容
- 隐式常量/非常量运算符布尔
- 非常量变量只读位置的赋值
- C++中的动态对象与非动态对象
- 是否可以同时声明一个类成员的常量/非常量?
- 我用c ++做了一个有点非正统的计算器,如何让它变得更好