用C ++编写计算器

时间:2016-10-30 13:20:31

标签: c++

我是C ++编程的新手(我已经进入了一周)并且我试图制作一个基本的计算器。每当我尝试运行代码时,我都会得到0.我在这部分中遇到了一些问题:

奖金问题:此外,交换机是否有办法使用字符串?

int finalnumber;
char number(int firstnumber, int secondnumber, int finalnumber, char operation);

char number(int firstnumber, int secondnumber, int finalnumber, char operation)
{
    switch (operation)
    {
    case '+':
        finalnumber = firstnumber + secondnumber;
        break;

    case '-':
        finalnumber = firstnumber - secondnumber;
        break;

    case '*':
        finalnumber = firstnumber * secondnumber;
        break;

    case '/':
        finalnumber=firstnumber / secondnumber;
        break;

    default:
        cout << "pls eneter a valid operation";
    }
    return finalnumber;
}

2 个答案:

答案 0 :(得分:2)

你不需要通过&#34; finalnumber&#34;作为方法的参数,最好在方法中声明它。

你不能在开关案例中使用字符串,但是你可以声明 enum 并使用它,你可以尝试google它,但我建议你这样做开始时更简单的东西。

如果你想要很好的精度,你的方法应该是返回类型double,并且输入也应该加倍(或者你可以在进行除法时首先乘以1.0(第一个* 1.0 /秒)。

double calculator(double first, double second, char sign)
{
    double result = 0;

    switch (sign)
    {
    case '+':
        result = first + second;
        break;

    case '-':
        result = first - second;
        break;

    case '*':
        result = first * second;
        break;

    case '/':
        result = first / second;
        break;

    default:
        std::cout << "Please enter a valid operation.";
    }
    return result;
}

答案 1 :(得分:0)

在这种情况下,最好使用if运算符,因为在这种情况下,我认为它更灵活。

#include "stdafx.h"
#include <iostream>
using namespace std;


int main()
{

start:
    printf("This program is Calculator, Works only for integer\nEnter First Number\n");
    int a, exp;
    cin >> a;
    exp = a;
    printf("Enter the Operation (+,-,*,/,Shift + 5 for percent,^)\n--->>");
    char b;
    cin >> b;
    printf("Enter the Second Number\n--->>");
    int c;
    cin >> c;
    int d;
     if (b == '-')
    {
        d = a - c;
        printf("%i - %i = %i \n\n", a, c, d);
    }
    else if (b == '+')
    {
        d = a + c;
        printf("%i + %i = %i \n\n", a,  c, d);

    }
    else if (b == '/')
    {
        d = a / c;
        printf("%i / %i = %i \n\n", a,  c, d);

    }
    else if (b == '*')
    {
        d = a * c;
        printf("%i * %i = %i \n\n", a,  c, d);

    }
    else if (b == '%')
    {
        d = a * (c / 100);                              
        printf("%i's  %i percent is %i \n\n", a,c,d);
    }
    else if (b == '^')
    {
        int k = 1;

        if (c == k)
        {
            d = a;
            printf("%i ^ %i = %i \n\n", a, c, d);
        }
        else if (k < c) {
            exponent:
            k = k + 1;
            a = a * exp;
            d = a;
         if (k < c) {
            goto exponent;
        }
         else if (k = c) {
            printf("%i ^ %i = %i\n\n", exp, c, d);
        }

        }


        }




     goto start;
    return 0;
}