【问题标题】:simple c++ calculator with sqrt and pow?带有 sqrt 和 pow 的简单 c++ 计算器?
【发布时间】:2014-10-14 12:26:13
【问题描述】:

嗨,我是 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;
        }
    }
}

【问题讨论】:

  • 首先你想用什么语法来表示这些操作?
  • x ^ y 代表权力。对于 sqrt,y=0.5。 pow(x,y)
  • 包括 pow 和 sqrt 函数
  • 就像一个计算器...一个输入像 25 和答案显示 5 。战俘也是如此
  • 唐,这甚至不需要,如果使用 C++,它们包含在 math.h 中(可能在 C 中,无法确认)

标签: c++ calculator


【解决方案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);

【讨论】:

    【解决方案2】:

    只需使用 cmath(或 math.h,因为您已经包含)中提供的函数:

    cout << "square root of  " << num1 << ": " << sqrt(num1);
    

    ...

    cout << num1 << " raised to the power " << num2 << ": " << pow(num1, num2);
    

    【讨论】:

    • 如果我将它添加到我的程序中,当我运行程序时它会显示 num1 op num 2 我应该使用 4sqrt4 作为 sqrt ...
    • 我没有关注“4sqrt4”
    • 你真的不需要 num2 用于 sqrt,所以你可以简单地忽略它。试试看,自己看看。
    • 你确实需要 num2。如果您不使用,您将只能计算平方根。如果您希望能够计算任何值,请使用 pow。看我的回答。
    【解决方案3】:

    您可以添加几个案例:

    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);
    

    记住:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多