我刚开始学c++,做了一个计算器。我可以做什么或如何改进我的代码/了解更多信息?

I just started c++ and made a calculator. What or how can I improve my code/ learn more?

所以我尝试制作一个简单的计算器,可以输入 2 个浮点数并进行基本运算(加法、减法、除法、乘法)。这是我第一次在不从教程中复制整个内容的情况下编写代码。我确实复制了一些错误修复和其他东西,但大部分是我自己做的。我想要批评,我想知道我可以做得更好。

#include <iostream>
#include <ctype.h>
#include <string>

using namespace std;

char start;
float num1, num2, result;
char op;

int menu(){
    cout<<"\nstart the program? \ny or n:\t";
    cin>>start;
    return 0;
}

int input_number(){
    cout<<"\nenter the first number: ";
    cin >> num1;
    while (!cin){
        cout<<"Error. Number of elements must be numerical. Try again: " << endl;
        cin.clear();
        cin.ignore(256, '\n');  
        cin >> num1;
    }
    cout<<"\nenter the second number ";
    cin >> num2;
    while (!cin){
        cout<<"Error. Number of elements must be numerical. Try again: " << endl;
        cin.clear();
        cin.ignore(256, '\n');  
        cin >> num2;
    }
    return 0;
}

int input_op(){
    cout<<"\nenter which operation you want to execute (+,-,/,*): ";
    cin>>op;
    switch (op)
    {
    case '+': result= num1+num2; break;
    case '-': result= num1-num2; break;
    case '*': result= num1*num2; break;
    case '/': result= num1/num2; break;
    default: cout<<"wrong input";
        break;
    }
    return 0;
}

int main(){
    cout<<"-----Calculator X-----";
    menu();
    if (start=='y' || start== 'Y'){
        input_number();
        input_op();
        cout<<"the result is : "<<result<<'\n';
        menu();
    }
    else{
        cout<<"exiting program";
        return 0;}
}
  • 函数不需要return0,只需将它们声明为voidreturn.

    • 除了int main()
  • cin>>num; while(!cin){cin>>num;}可以合并为while(!(cin>>num))

  • 忽略 256 字符可能不够

    • 改用std::numeric_limits<std::streamsize>::max()
  • 对于ctype.h,对应的c++头文件是cctype()


  • 您实际上可以 return 结果而不是存储在全局状态中。
    • bool menu()std::pair<int,int> input_number()char input_op()
  • input_number 可能会得到一个数字而不是 2 个(并且被调用两次)
  • 你没有检查 op 是否有效(不同于数字输入)

想在需要时向 @apple apple said. You don't need to define all the variables in the global scope(start, num1, etc) in this specific case, just use them inside a functions or pass them to a functions 添加一些内容。希望对您有所帮助:^)