Home > Software design >  Very basic calculator issues
Very basic calculator issues

Time:02-15

I'm a fairly new to c . I'm trying to create a very basic calculator and the results I'm getting are completely wrong. I've come to a standstill after 2 hours of trying everything in my knowledge. What am I doing wrong?

#include <iostream> 
using namespace std; 

int main()      
{                    

    int a = 0.0;
    int b = 0.0;
    float sum = 'a'   'b';
    float diff = 'a' - 'b';
    float prod = 'a' * 'b';
    float quot = 'a' / 'b';
    float rem = 'a' % 'b';
    
    //Input
    cout << "Enter a number: " << endl;
    cin >> a;
    cout << "Enter another number: " << endl;
    cin >> b;
    
    
    cout << a << "   " << b << " = " << sum <<endl;
    cout << a << " - " << b << " = " << diff <<endl;
    cout << a << " / " << b << " = " << quot <<endl;
    cout << a << " * " << b << " = " << prod <<endl;
    cout << a << " % " << b << " = " << rem <<endl;

    
    
    return 0;
}             

CodePudding user response:

you are calculating with character literals. 'a' is not the same as a here. remove the quotes when calculating, but add them when you print the actual literal "a"

float sum = 'a'   'b';

You are calculating the ASCII value of the character "a" (which is 65) with the ASCII value of "b" (which is 66)

It should be

float sum = a   b;

instead.

When you print the values, you did the reverse:

cout << a << "   " << b << " = " << sum <<endl;

You want it to be

cout << "a" << "   " << "b" << " = " << sum <<endl;

instead. You want to print characters for the equation and only a number for the result.

You also calculate the values of a and b before they have an actual value. You should put the calculation after you enter them.

CodePudding user response:

Fixed, by moving the calculations after the input; and by using variables, not literals.

#include <iostream> 
using namespace std; 

int main()      
{                    
    int a = 0.0;
    int b = 0.0;
    
    //Input
    cout << "Enter a number: " << endl;
    cin >> a;
    cout << "Enter another number: " << endl;
    cin >> b;
    
    float sum  = a   b;
    float diff = a - b;
    float prod = a * b;
    float quot = a / b;
    float rem  = a % b;

    cout << a << "   " << b << " = " << sum <<endl;
    cout << a << " - " << b << " = " << diff <<endl;
    cout << a << " / " << b << " = " << quot <<endl;
    cout << a << " * " << b << " = " << prod <<endl;
    cout << a << " % " << b << " = " << rem <<endl;

    return 0;
}             
  •  Tags:  
  • c
  • Related