I am making a c++ program which functions as a calculator. Everything works except for the division function, which adds the doubles for some reason. Anyone have a fix?
I have tried explicitly casting to a double and banging my head on my desk. Here are a few snippets of my code.
#include "pch.h"
#include <iostream>
using namespace std;
void divide()
{
//first number
cout << "What is the numerator?";
double firstNum = 0;
cin >> firstNum;
//second number
cout << "What is the denominator?";
double secNum = 0;
cin >> secNum;
//multiplying
double answer = firstNum/(double)secNum;
cout << "Your answer is " << answer << ".";
}
int main()
{
//asks for what operation user would like to use
cout << "Do you want to add, subtract, divide, or multiply? Type [1] for add, [2] for subtract, [3] for divide, and [4] for multiply(minus the brackets).";
double opquery = 0;
cin >> opquery;
// if division
if (opquery == 3)
{
divide();
return 0;
}
}
I would have expected something like 4/4
to equal 1
, but it just returns addition
UPDATE: FULL CODE CAN BE FOUND AT https://github.com/hoverdoge/cppcalculatorerror/blob/master/code
Actually, the code you share here is ok and the result of 4/4=1.
But the code you share in the github has something different. Remove the
;
afterif (opquery == 1);
The program can work normally.
Changes from:
if (opquery == 1);
{
add();
return 0;
}
To:
if (opquery == 1)
{
add();
return 0;
}
Note: When you add the extra ;
after if(xxx), whatever the value of opquery is, the main method will execute steps below:
cout << "xxx...";
int opquery = 0;
cin >> opquery;
add();
return 0;
That's why this issue occurs.