如何使用if else和函数在c ++中制作计算器?

时间:2018-11-24 14:57:41

标签: c++

我是一名新贡献者,在这里我试图制作一个简单的计算器,但是我的代码中有错误。当我编译代码时,我得到:

Error: C:\Users\IJLAL\Documents\collect2.exe    [Error] ld returned 1 exit status while compiling 

以防万一,在我按下Dev C ++中的编译按钮或F11时,这是错误的屏幕截图: enter image description here

这是我的代码:

#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.......";
    }
}

请告诉我该问题的解决方案,以便我可以成功地编译代码。如果有更好的解决方案来制作初学者水平的简单计算器,请在回答中提及。

4 个答案:

答案 0 :(得分:2)

您离结果不远。问题是您尚未定义函数fun()。此外,在您定义的函数op()中,您不使用输入的运算符。

所以首先要做的就是更改函数的签名:

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

然后,您需要在main()中调用函数,同时传递用户请求的操作:

fun(op, a, b);

最后,您需要更改所有if来检查op是否为匹配的运算符:

void fun(char op, float a, float b)
{
    if(op=='+')
    {
        ...
    }
    else if(op=='-')
    {
...

然后您应该会得到预期的结果。

Online demo

其他信息

  • if (a+b)仅使用用户的两个值来计算表达式,如果它不是零,则认为它是true。
  • 该程序正常运行后,您就可以查找switch语句

答案 1 :(得分:1)

您可以使用其他功能来制作更好的计算器。您可以使用此代码。希望这段代码对您有所帮助。
标头<iomanip>C++标准库的输入/输出库的一部分,而<math.h>在执行数学运算时使用。

#include<iostream>
#include<conio.h>
#include<math.h>
#include<iomanip>
  char op;
using namespace std;
void sum()
   {

    int sum = 0;
    int n;
    int numberitems;
    cout << "Enter number of items: \n";
    cin >> numberitems;

    for(int i=0;i<numberitems;i++)
    {
        cout<< "Enter number "<<i<<":\n\n" ;
        cin>>n; 
        sum+=n;
    }
    cout<<"sum is: "<< sum<<endl<<endl;

    }
void diff()
    {
     int diff;
     int n1,n2;
     cout<<"enter two numbers to find their difference:\n\n";
     cout<<"enter first number:";
     cin>>n1;
     cout<<"\nenter second number:";
     cin>>n2;
     diff=n1-n2;
     cout<<"\ndifference is:"<<diff<<endl<<endl;
     }

void pro()

    {
     int pro=1;
     int n;
     int numberitems;
     cout<<"enter number of items:\n";
     cin>>numberitems;
     for(int i=0;i<=numberitems;i++)
     {
             cout<<"\nenter item "<<i<<":";
             cin>>n;
             pro*=n;
     }

     cout<<"product is:"<<pro<<endl<<endl;    
     }

 void div()
     {
      int div;
      int n1;
      int n2;
      cout<<"enter 2 numbers to find their quotient\n\n";
      cout<<"enter numerator:";
      cin>>n1;
      cout<<"\nenter denominator:";
      cin>>n2;
      div=n1/n2;
      cout<<"\nquotient is:"<<div<<endl<<endl;
      }      

void power()
     {     
     long int p;
     int res=1,n; 
     cout<<"enter number:";
     cin>>n;
     cout<<"\nenter power:";
     cin>>p;
     for(int i=1;i<=p;i++)
     {
      res=n*res;
     }
      cout<<n<<"\n power "<<p<<" is :"<<res<<endl;
     } 

void sq()
     {
     float s;
     int n;
     cout<<"enter number to find its square root:";
     cin>>n;
     s=sqrt(n);
     cout<<"\nsquare root of "<<n<<" is :"<<s<<endl;
     }
 void fact()
     {
      long int f=1;
      int c=1,n;
      cout<<"enter number to find its factorial:";
      cin>>n;
      while(c<=n)
      {
                 f=f*c;
                 c+=1;
      }     
                 cout<<"\nfactorial of "<<n<<" is :"<<f<<endl;     
      }
void expo()
     {
          long double res=1,p; 
     double e=2.718281828;     
     cout<<"enter power of exponential function:";
     cin>>p;
     for(int i=1;i<=p;i++)
     {
      res=e*res;
     }
      cout<<" e^ "<<p<<" is :"<<res<<endl;

           }
int main()
{   


    system("cls");
    do
    {

    system("pause");              
    system("cls");    
    cout<<"***which operation you want to perform***\n";
    cout<<"press 0 for exit\n";
    cout<<"press 1 for addition \n";
    cout<<"press 2 for subtraction\n";
    cout<<"press 3 for multiplication\n";
    cout<<"press 4 for division\n";
    cout<<"press 5 for power calculation\n";
    cout<<"press 6 for square root \n";
    cout<<"press 7 for factorial calculation\n";
    cout<<"press 8 for exponential calculation\n";
    cout<<"press option:";
    cin>>op;
    switch(op)
    {
              case '1':
              sum();

              break;
              case '2':
              diff();
              break;
              case '3':
              pro();
              break;
              case '4':
              div();
              break;
              case '5':
              power();
              break;
              case '6':
              sq();
              break;
              case '7':
              fact();
              break;
              case '8':
              expo();
              break;     
              case '0':
              exit(0);    
              default:
              cout<<"invalid input"  ;
              system("cls");
    } 
    }

    while(op!='0');

                    getch();
                    }

答案 2 :(得分:0)

我不会批评您的解决方案,因为您提到了“请在回答中提及更好的解决方案” 这是我的解决方案,带有注释,可以使您了解每个语句的作用。

#include <iostream>
using namespace std; 
// I am  going to show How to Design a program
// We have to break down our progress a bit by bit
// and do the progress of one thing with function
// For calculator we have to take input from user keyboard twice,
// And an opperator from user
int userInput() // this requires to get input from user keyboard
{
 cout << "Enter a number: ";
 int no{};
 cin >> no;
 return no;
}
char userOpr() // Using type char to store the ASCI Opperator means requires char to store +,*,/,-
{
 cout << "Enter opperator: ";
 char opr{};
 cin >> opr;
 return opr;
}
int calculate(int input1, char opper, int input2)
{
 if (opper == '+')
 {
 return input1 + input2;
 }
 else if (opper == '-')
 {
 return input1 - input2;
 }
 else if (opper == '*')
 {
 return input1 * input2;
 }
 else if (opper == '/')
 {
 return input1 / input2;
 }
 return 0;
}
int main()
{
 // get the first no. from user
 // getUserInput();
 // get the math oppperator from the user
 // getMathOpperator();
 // get the second no. from the user
 // getUserInput();
 // calculate the values
 // calculateResults();
 // print out the results
 // printResults();
 cout << "Hello This is a simple calculator program Designed by Shankhui!\n\n";
 while (true)
 {
 int input1{ userInput() };
 int input2{ userInput() };
 char opper{ userOpr() }; // Using type char to store the ASCI Opperator means requires char to store +,*,/,-
 cout << input1 << " " << opper << " " << input2 << " = " << calculate(input1, opper, input2) << '\n' << '\n';
 }
 return 0;
}

答案 3 :(得分:0)

嘿,我仍然是C ++的新手,但希望能对您有所帮助,我使用while循环来循环计算器,但是例如当用户尝试输入字母而不是数字时,我没有很好的错误处理程序。 / p>

#include <iostream>
#include <cmath>
using namespace std;

int result (int a, int b, char op);

int main()
{


char optr, choice;
int nr1, nr2;

while (true){
cout << "Enter first number: ";
cin >> nr1;
cout << "Enter an operator (+ - / * %) : ";
cin >> optr;
cout << "Enter second number: ";
cin >> nr2;

result (nr1, nr2, optr);
cout<<"Would you like to perform other calculation?(Y/N): ";
cin >> choice;

if (choice =='N'||choice =='n'){
    break;
    }
}

}


int result (int a, int b, char op)
{
int result;

if (op == '+'){
result = a + b;
cout << "Result to " << a << " + " << b << " = " << result << endl;
} else if (op == '-'){
result = a - b;
cout << "Result to " << a << " + " << b << " = " << result << endl;
} else if (op == '*'){
result = a * b;
cout << "Result to " << a << " * " << b << " = " << result << endl;
} else if (op == '/'){
result = a / b;
a / b;
cout << "Result to " << a << " / " << b << " = " << result << endl;
} else if (op == '%'){
result = a % b;
cout << "Remainder to " << a << " % " << b << " = " << result << endl;
} else {
cout <<"Error 404: " << a << op << b <<" Wrong input format. Program terminated."          << endl;


// i still dont know how to properly use error handling

}

}