计算器在C ++中使用函数

时间:2018-12-04 04:17:29

标签: c++

我正在使用函数制作一个简单的计算器,但是出现错误。我试图解决它不能这样做。我一次又一次地尝试,但我不明白为什么要这么做。我正在使用Dev C ++编译器。我有错误的语句if(a-b)

#include<iostream>
using namespace std;
void fun(float a, float b); 
int main()
{   
    float a, b, sum, sub, mul, divide, mod;
    char op;

    //operands and operators are enterd by the user
    cout<<"Enter any two operands with operator=";
    cin>>a>>op>>b;
    fun(a, b);
    return 0;
}
void op(float a, float b)
{
    if(a+b)
    {
        float sum=a+b;
        cout<<"\nAddition of two numbers is="<<sum;
    }
    else if(a-b)
    {
        float sub=a-b;
        cout<<"\nSubtraction of two numbers is="<<sub;
    }
    else if(a*b)
    {
        float mul=a*b;
        cout<<"\nMultiplication of two numbers is="<<mul;
    }
    else if(a/b)
    {
        float divide=a/b;
        cout<<"\nDivision of two number is="<<divide;
    }
    else
    {
        cout<<"\nInvalid operator.......";
    }
}

编译器错误:

calculator.cpp:(.text+0x68): undefined reference to `fun(float, float)`.
[Error] ld returned 1 exit status

2 个答案:

答案 0 :(得分:2)

您可能想这样声明fun

void fun(float a, char op, float b);

并使用相同的签名进行定义。

然后在该函数内部,将if (a+b)之类的条件替换为if (op == '+')之类的条件,并对其他运算符进行类似的更改。

为了便于阅读,您应该在运算符周围放置一些空格。例如:

cin >> a >> op >> b;
float sum = a + b;

最后,摆脱所有未使用的变量。总的来说,您有sum, sub, mul, divide, mod

答案 1 :(得分:2)

您的代码有4个问题:

  1. 首先,您声明了void fun(float, float),但未定义它。而是定义void op(float, float)

    编辑:c++中的运算符重载无法通过这种方式工作:检查cppreference: operator overloading

  2. void op(float, float)中的代码对我来说似乎毫无意义。它不具有计算器的功能。您应该使用在op中定义的变量int main()

  3. using namespace std; is not a good habit

  4. 您没有检查输入/输出是否成功。

因此:

#include <iostream>

void calculate(float a, char op, float b);
int main()
{
    float a, b; /* These are useless: sum, sub, mul, divide, mod;*/
    char op; //operands and operators are entered by the user 

    std::cout.exceptions(std::cout.failbit);
    std::cin.exceptions(std::cin.badbit);
    std::cerr.exceptions(std::cerr.failbit);

    std::cout << "Enter any two operands with operator="; 

    if (std::cin >> a >> op >> b)
        calculate(a, op, b);

    return 0;
}

void calculate(float a, char op, float b)
{
    switch(op) {
        case '+':
            std::cout << "\nAddition of two numbers is " << (a + b);
            break;
        case '-':
            std::cout << "\nSubtraction of two numbers is " << (a - b);
            break;
        case '*':
            std::cout << "\nMultiplication of two numbers is= "<< (a * b);
            break;
        case '/':
            std::cout << "\nDivision of two numbers is= "<< (a / b);
            break;
        default:
            std::cerr << "\nUnkown operator!";
    }
}

您确实应该阅读一些有关C++的优秀教程书籍,并阅读cppreference之类的在线文档以了解C++