基本控制台计算器(在变量中存储字符串)C ++

时间:2015-09-27 04:56:33

标签: c++

我试图用C ++创建一个基本的控制台计算器。我在从cin命令的变量中存储字符串时遇到了一些麻烦。

这是一个澄清的程序:

#include <iostream>
using namespace std;

int main()
{
    string type_cal;

    cout << "Please enter the type of calculation you would like to use: \n";
    cout << "1. Addition \n";
    cout << "2. Subtraction \n";
    cout << "3. Multiplication \n";
    cout << "4. Division \n \n";

    cin >> type_cal;

    if (type_cal = "Addition" or "1")
    {
        int a;
        int b;
        int sum;

        cout << "Please enter a number to add: \n";
        cin >> a;

        cout << "Please enter another number: \n";
        cin >> b;

        sum = a + b;

        cout << "The sum of those numbers is: " << sum << endl;

        return 0;
    }
}

目前我处于加入阶段,因为我最近遇到了这个问题。快速回答将不胜感激,谢谢!

3 个答案:

答案 0 :(得分:1)

if(type_cal =“Addition”或“1”)根本没有意义。

if(type_cal == "Addition" || type_cal == "1") {
}

答案 1 :(得分:0)

好的我发现了问题,或实际上是用作||在c ++(感谢aerkenemesis)中,=与==不同,这意味着等于(另一个感谢Lorehed)。程序工作正常。

答案 2 :(得分:0)

对于那些好奇的人,这是我的简单计算器的新版和修订版:

#include <iostream>
using namespace std;

float addition();
float subtraction();
float multiplication();
float division();

int main()
{
    string type_cal;

    cout << "Please enter the type of calculation you would like to use: \n";
    cout << "1. Addition " << endl;
    cout << "2. Subtraction " << endl;
    cout << "3. Multiplication " << endl;
    cout << "4. Division" << endl << endl;

    cin >> type_cal;

    if(type_cal == "Addition")
    {
        addition();
    }

    if(type_cal == "Subtraction")
    {
        subtraction();
    }

    if(type_cal == "Multiplication")
    {
        multiplication();
    }

    if(type_cal == "Division")
    {
        division();
    }

    return 0;
}



float addition()
{
    float a;
    float b;
    float sum;

    cout << "Please enter a number to add: " << endl;
    cin >> a;

    cout << "Please enter another number: " << endl;;
    cin >> b;

    sum = a + b;

    cout << "The sum of those numbers is: " << sum << endl;
}




float subtraction()
{
    float c;
    float d;
    float difference;

    cout << "Please enter a number to subtract: \n";
    cin >> c;

    cout << "Please enter another number: \n";
    cin >> d;

    difference = c - d;

    cout << "The difference of those numbers is " << difference << endl;
}




float multiplication()
{
    float e;
    float f;
    float product;

    cout << "Please enter a number to multiply: \n";
    cin >> e;

    cout << "Please enter another number: \n";
    cin >> f;

    product = e * f;

    cout << "The product of those numbers is " << product << endl;
}




float division()
{
    float g;
    float h;
    float quotient;

    cout << "Please enter a number to divide: \n";
    cin >> g;

    cout << "Please enter another number: \n";
    cin >> h;

    quotient = g / h;

    cout << "The quotient of those numbers is " << quotient << endl;
}