C++ Calculator always returns 7208640 - c++

This is the code for my calculator:
#include <iostream>
using namespace std;
int main()
{
int fNumber, sNumber, sum;
string op;
cout << "You will be asked for two numbers and the operator to use on them.\nCurrently supported operators are:\n";
cout << " Addition: +\n Subtraction: -\n Multiplication: *\n Division: \\\n Modulo: %\n\n";
cout << "First Number: ";
cin >> fNumber;
cout << "\nSecond Number: ";
cin >> sNumber;
cout << "\nOperator: ";
cin >> op;
if(op == "+"){
int sum = fNumber + sNumber;
} else if(op == "x" || op == "*"){
int sum = fNumber * sNumber;
} else if(op == "/"){
int sum = fNumber / sNumber;
} else if(op == "-"){
int sum = fNumber - sNumber;
} else if(op == "%"){
int sum = fNumber % sNumber;
} else{
cout << "\nPlease use a correct Operator\n";
return 1;
}
cout << "\n" << fNumber << " " << op << " " << sNumber << " = " << sum << "\n";
return 0;
}
I have absolutely no idea why, but for some reason, whatever numbers or operators I give it it returns "7208640" as the answer:
You will be asked for two numbers and the operator to use on them.
Currently supported operators are:
Addition: +
Subtraction: -
Multiplication: *
Division: \
Modulo: %
First Number: 6
Second Number: 2
Operator: /
6 / 2 = 7208640
Process returned 0 (0x0) execution time : 4.612 s Press any key to
continue.

if(op == "+"){
int sum = fNumber + sNumber;
should be
if(op == "+"){
sum = fNumber + sNumber;
and the same for all the other int sum except the first. You declare a variable once, not every time you use it.

As above, remove the int declarations from inside the if statements.
Also, please change the name of the sum variable to something like "answer." A result from subtraction, multiplication, division and modulo is referred to as difference, product, quotient, and remainder, respectively.

Related

C++ Basic Calculator

I'm new to C++ and programming in General. I was assigned to make a calculator for my C++ class and this is what I have so far.
#include <iostream>;
#include <iomanip>;
using namespace std;
int main() {
double x,y;
char op;
cout << "Enter Expression:";
cin >> x >> op >> y;
if (op = '+')
{
cout << "Result:" << x + y << endl;
}
else if (op = '-') {
cout << "Result:" << x - y << endl;
}
else if (op = '*') {
cout << "Result:" << x*y << endl;
}
else if (op = '/') {
cout << "Result:" << x / y << endl;
}
else if (op = '%') {
cout << "Result:" << x % y << endl; // <--- line 23
}
else {
return 0;
}
}
The x and y variables on line 23 both have errors saying that the expression must have an integral or unscoped enum type and I don't understand why.
The % operation is defined only for integer values. You cannot apply it for doubles. Also you have a typical novice mistake: In C++ operator = is assignment operator a = b mean get b value and put it in a. But operator == is comparison operator, a == b mean if a equally b return true. If you want to compare values use ==, not =.
With floating point division there is no remainder. What should be the result of 2.5 % 1.2?
You could use ints for that case:
else if (op == '%') {
cout << "Result:" << (int)x % (int)y << endl;
}
but note that when the user types 2.5 % 1.2 this will show the result for 2 % 1.
PS: Also note that you have = (assignment) in the conditions when it should be == (comparison).
You are using % for double, it is only for integers.
If you want to use same functionality for double. you can use fmod()
double z = fmod(x,y);
You should modify your code to below
#include <iostream>;
#include <iomanip>;
using namespace std;
int main() {
double x,y;
char op;
cout << "Enter Expression:";
cin >> x >> op >> y;
if (op == '+')
{
cout << "Result:" << x + y << endl;
}
else if (op == '-') {
cout << "Result:" << x - y << endl;
}
else if (op == '*') {
cout << "Result:" << x*y << endl;
}
else if (op == '/') {
cout << "Result:" << x / y << endl;
}
else if (op == '%') {
cout << "Result:" << fmode(x,y) << endl;
}
else{
return 0;
}
}
The remainder operator % does not work for operands of type double (cf., for example, cppreference.com/Multiplicative operators):
For the built-in operator %, lhs and rhs must both have integral or
unscoped enumeration type
You could write static_cast<int>(x)%static_cast<int>(y) instead.
Further, note that = is assignment operator; for comparisons (as in your case with if (op = '%')), use equality operator ==, i.e. if (op == '%').

C++ Do-while loop stopping

I got an assignment where we make a cmd prompt show up and display a flashcard game for multiplication. After inputting a correct answer a prompt shows up and asks the user to go "Again? Y/N." after the second input answer the prompt to ask the user doesn't show up and it's stuck on a "congratulations" message. This happens when I write in code to randomly generate two numbers for the game twice. one outside the while loop, and one inside while loop. If I leave one out the 2nd code for the random numbers it will run fine but will only display the same numbers over again. what I'm asking is how do I fix it so that it won't get stuck after the second answer input?
sample code below:
#include <iostream>
using namespace std;
int main()
{
int num1, num2, ans, guess, count = 0;
char choice;
num1 = rand() % 12 + 1;
num2 = rand() % 12 + 1;
//first number generator.
ans = num1 * num2;
do
{
{
cout << num1 << " X " << num2 << " = ";
cin >> guess;
cout << "Wow~! Congratulations~! ";
count++;
num1 = rand() % 12 + 1;
num2 = rand() % 12 + 1;
//second number generator.
} while (guess != ans);
cout << "\nAgain? Y/N: ";
cin >> choice;
} while ((choice == 'y') || (choice == 'Y'));
//after two turns the loop stops. Can't make a choice.
cout << " Thanks for playing! Number of tries:" << count << endl;
return 0;
}
I'd guess the problem is because your loops aren't quite what you think they are.
do
{
The code above has started a do loop.
{
I suspect you intended to start another (nested) do loop here--but you left off the do, so it's just a block that gets entered, executed, and exited. Useless and pointless in this case.
cout << num1 << " X " << num2 << " = ";
cin >> guess;
cout << "Wow~! Congratulations~! ";
count++;
num1 = rand() % 12 + 1;
num2 = rand() % 12 + 1;
//second number generator.
} while (guess != ans);
You've formatted this as if the while were closing the nested do loop--but since you didn't actually create a nested do loop, this is just a while loop with an empty body. Its meaning would be more apparent with a little re-formatting:
// second number generator
}
while (guess != ans)
/* do nothing */
;
The problem can be found here:
do
{
{
cout << num1 << " X " << num2 << " = ";
cin >> guess;
As you can see, the second scope has no do statement. As a result it is only a codeblock.
You can solve it by writing a do statement for the second code block.
Because the do is not present in the second bracket ({), the while is interpreted as a while loop:
while (guess != ans);
or
while (guess != ans) {
}
this thus keeps looping until guess is not equal to ans. But since in the loop does not modify any of the two variables, the loop will keep iterating.
Other errors: note that the program is still incorrect, since it will claim you have answered the question, regardless of the answer. You can fix it by implementing this as follows:
int main()
{
int num1, num2, ans, guess, count = 0;
char choice;
do {
num1 = rand() % 12 + 1;
num2 = rand() % 12 + 1;
ans = num1 * num2;
do {
cout << num1 << " X " << num2 << " = ";
cin >> guess;
if(guess == ans) {
cout << "Wow~! Congratulations~! ";
} else {
cout << "No, wrong!\n";
}
count++;
} while (guess != ans);
cout << "\nAgain? Y/N: ";
cin >> choice;
} while ((choice == 'y') || (choice == 'Y'));
//after two turns the loop stops. Can't make a choice.
cout << " Thanks for playing! Number of tries:" << count << endl;
return 0;
}

Basic calculator C++, there is no error but code only returns 0 regardless of the value

I'm fairly new to coding and I wanted to attempt a basic calculator after weeks of studying, however this code only returns the value of 0 regardless of the number or function input.
I'm not sure what I'm doing wrong.
#include<iostream>
using namespace std;
int main(){
int number;
int secNumber;
int sum;
string function;
string add;
string subtract;
string divide;
string modulus;
string multiply;
cout << "what will be your first number?" << endl;
cin >> number;
cout << "what will be your second number?" << endl;
cin >> secNumber;
cout << "what would you like to do with these number?" << endl;
cin >> function;
if (function==add)
sum = number + secNumber;
else if (function==subtract)
sum = number - secNumber;
else if(function== divide)
sum = number/secNumber;
else if(function== multiply)
sum = number*secNumber;
else if(function==modulus)
sum = number%secNumber;
cout << "Your sum is "<<sum << endl;
return sum;
}
You're not initializing add, subtract, etc. Those strings are all empty. So regardless of what function you're entering, they're not going to compare equal against an empty string.
Instead, compare against string literals:
if (function == "add") {
sum = number + secNumber;
}
else if (function == "subtract") {
...
}
...
It would also be helpful to add an error message at the end, in case the user enters an invalid function:
else {
std::cout << "Unknown function " << function;
}

C++ Coding Issue

I am getting this error as I am trying to compile my code. I am trying to make a simple calculator and I am having some trouble removing this final error. Any and all help is appreciated.
The error I am getting is as follows expected constructor, destructor, or type conversion before '(' token
#include <iostream>
#include <string.h>
using namespace std;
int intevaluate(int Left, char Operation, int Right);
void Intro();
int intLeft;
int intRight;
char charOperation;
int intAddition;
int intSubtraction;
int intMultiplication;
int intDivision;
void Intro()
{
cout << "These are the arithmetic operations you can choose to enter ";
cout << " + for addition\n - for subtraction\n * for multiplication\n and / for division\n";
}
intevaluate(intLeft, charOperation, intRight)
{
intAddition = intLeft + intRight;
intSubtraction = intLeft - intRight;
intMultiplication = intLeft * intRight;
intDivision = intLeft / intRight;
if (charOperation == "+")
{
cout << "The answer is " << intAddition;
}
else if (charOperation == "-")
{
cout << "The answer is " << intSubtraction;
}
else if (charOperation == "*")
{
cout << "The answer is " << intMultiplication;
}
else if (charOperation == "/") && ( Left || Right != 0)
{
cout << "The answer is " << intDivision;
}
else if (charOperation == "/") && ( Left || Right == 0)
{
cout << "You cannot divide by zero ";
}
}
int main()
{
cout << "Please enter an integer value and press enter: ";
cin >> intLeft;
cout << "\nPlease enter another integer value and press enter: ";
cin >> intRight;
Intro();
cout << "\nPlease enter an arithmetic operation from the list above and press enter: ";
cin >> charOperation;
intevaluate(intLeft, charOperation, intRight);
return 0;
}
You have messed up the function argument names.
if (Operation == +)
{
// ...
}
What is Operation? You pass the function a char with argument name
charOperation
not
Operation
You can't compare characters like that. You must do
if(charOperation == '+')
and so on.

check if my variable is not integer in "if" statement in c++

I have written c++ code and this is part of it:
int flag8=1,
tmp,
part;
.
.
.
if(part > 7 || !(int)tmp || tmp < 0){
cout << "ERROR !!!\n";
flag8=0;
break;
}
how can I check my tmp variable is integer or not?
I want to say my if statement be true if part>7 or tmp is not integer or tmp<0.
thank you very much.
edit:
this is my whole code:
#include <iostream>
using namespace std;
int base2toten(int nums);
int base8toten(int num);
////////////////////////////////////////////
/* FUNCTION: CONVERTING BASE 2 TO 10 */
////////////////////////////////////////////
int base2to10(int nums){
int base2,
digits,
base10=0,
parts,
powers=1,
flag2=1;
cout << "Enter num base 2: ";
cin >> base2;
//if(!(int)base2 && base2 < 0 || !(int)base2 && base2 > 1){
// cout << "OUT OF RANGE"
//}
digits = base2;
while(digits){
parts = digits % 10;
if(parts > 1 || !(int)base2 || base2 < 0){
cout << "The number you have entered is not base 2 !!!\n";
flag2=0;
break;
}
digits /= 10;
base10 += powers * parts;
powers *= 2;
}
if(flag2){
cout << " \"base2\":\t" << base2 << "\n"
<< "\"base10\":\t" << base10 << endl;
}
}
///////////////////////////////////////////
/* FUNCTION: CONVERTING BASE 8 TO 10 */
///////////////////////////////////////////
int base8to10(int num){
int base8,
digit,
base10=0,
part,
power=1,
flag8=1;
cout << "Enter num base 8: ";
cin >> base8;
digit = base8;
while(digit){
part = digit % 10;
if(part > 7 || !(int)(base8) || base8 < 0){
cout << "The number you have entered is not base 8 !!!\n";
flag8=0;
break;
}
digit /= 10;
base10 += power * part;
power *= 8;
}
if(flag8){
cout << "\"base8\":\t" << base8 << "\n"
<< "\"base10\":\t" << base10 << endl;
}
}
//////////////////////////////////////////
/* FUNCTION: MAIN */
//////////////////////////////////////////
int main(){
int num,nums,a ,b,ans;
// cout << "What base you want to convert?\n"
cout << "*******************************************************\n"
<< "* BASE TWO: 2 *\n"
<< "* BASE EIGHT: 8 *\n"
<< "* BOTH BASE TWO AND EIGHT: 28 *\n"
<< "* BOTH BASE EIGHT AND TWO: 82 *\n"
<< "*******************************************************\n";
cout << "What base you want to convert? ";
cin >> ans;
if(ans != 2 && ans != 8 && ans != 28 && ans !=82){
cout << "Your answer in not acceptable!!!\n";
}
else if(ans == 2){
cout << "**********************************\n"
<< "* YOU'VE CHOSEN BASE 2 *\n"
<< "**********************************\n";
base2to10(a);
}
else if(ans == 8){
cout << "**********************************\n"
<< "* YOU'VE CHOSEN BASE 8 *\n"
<< "**********************************\n";
base8to10(b);
}
else if(ans == 28){
cout << "*********************************************\n"
<< "* YOU'VE CHOSEN BOTH BASE 2 AND 8 *\n"
<< "*********************************************\n";
base2to10(a);
base8to10(b);
}
else if(ans == 82){
cout << "*********************************************\n"
<< "* YOU'VE CHOSEN BOTH BASE 8 AND 2 *\n"
<< "*********************************************\n";
base8to10(b);
base2to10(a);
}
return 0;
}
Your question very likely asks for an XY-Problem. Since C++ is a typed language, the type you have used to declare a variable will always stay the same.
You'll need to check the state of your input stream, to test if the input was given in the correct format:
int tmp;
std::cin >> tmp;
if(!cin)
{
// user input was not parsable as integer value ...
}
If you want to specify particular numeric input formats, you can use stream manipulators (need to #include <iomanip>):
std::cin >> std::oct >> tmp; // Will parse integer from base 8 input
std::cin >> std::hex >> tmp; // Will parse integer from base 16 input
This is an example of what you want...Hope this helps...
This is only an example and you may have to check thoroughly and modify before using it in a real world app..
#include<stdio.h>
int main(){
int n=0;
char c;
do{
c=getchar();
if(c>='0' && c<='9'){
n=n*10;
n+=(c-48);
}
else if(c=='\n'){
break;
}
else{
printf("SOME THING WRONG");
break;
}
}while(1);
printf("%d ",n);
return 0;
}
Since you are saying base8 (from 0 to 7) modify the if statement with if(c>='0' && c<='7')