你好我是c ++的初学者,我想写一个简单的c ++计算器,我写了这个程序,我不知道如何添加pow和sqrt,请帮助我,
#include<conio.h>
#include<iostream>
#include<math.h>
using namespace std;
main()
{
double num1 , num2 ;
char op ;
while(1)
{
cout<<"type number,operator,number"<<endl;
cin>>num1>>op>>num2;
switch(op)
{
case '+':
cout<<"plural is "<<num1+num2<<endl;
break ;
case '-':
cout<<"subtract is "<<num1-num2<<endl;
break ;
case '*':
case 'x':
cout<<"multiple is "<<num1*num2<<endl;
break ;
case '/':
case '\\':
cout<<"division is "<<num1/num2<<endl;
break ;
default:
cout<<"operator is illegal"<<endl;
}
}
}
答案 0 :(得分:1)
只需使用cmath(或math.h中提供的函数,就像您已经包含的那样):
cout << "square root of " << num1 << ": " << sqrt(num1);
...
cout << num1 << " raised to the power " << num2 << ": " << pow(num1, num2);
答案 1 :(得分:1)
您可以添加几个案例:
case 'r': // For radicals
cout << pow(num1, 1.0/num2); // Note that if num2 == 2 this is the same as sqrt.
case 'p': // For pow
cout << pow(num1, num2);
请记住:
答案 2 :(得分:1)
在switch
case '^':
cout<<"Power is "<<pow(num1,num2);
break;
和
case 's': // you can't type in the sqrt symbol directly
cout<<"sqrt of num1:"<<sqrt(num1)<<"\nsqrt of num2:"<<sqrt(num2);