Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

Doing a lab on arithmetic expression... just need some guidance on why this isn't working the way it's supposed to?

+1 vote
asked Sep 29, 2020 by Jonathon Toppert (130 points)
//------------------------------------------------------------------------
// Lab3 (Simple If-Else)
// Due Date: Thur Sep. 24 at 10 pm (5 points)
// Grace Date: Wed. Sep. 30 at 10 pm (3 points)
//
// Name:    DO_01: Jonathon Toppert
//
// Course:  CS 1430, Section <DO_02: insert your section>, Fall 2020
//
// Purpose: In this lab, you will check the validity of a very simple
//          arithmetic expression.
//
// Input:   Two positive floating point numbers as operands and an
//          operator which is '+' or '-'.
//
// Output:  Message to say if expression is valid or invalid and
//          result of operation only if the expression is valid.
//------------------------------------------------------------------------
#include <iostream>
#include <iomanip>
using namespace std;

int main()
{

    cout << fixed << showpoint << setprecision(2);

    // DO_3: Declare the variables required for the expression
    // The expression has two floating point numbers called num1
    // and num2 and a char variable called arithmetic Operator
    // to be used as an operator

    float num1, num2;
    char arithmeticOperator;
    // Declare two boolean variables and initialize to false:
    // The first one will indicate whether the number(s) are valid or not,
    // called isValidNum.
    // The second one will indicate whether the operator is valid or not,
    // called isvalidOperator.

    bool isValidNum;
    bool isValidOperator;

    cout << "Enter an arithmetic expression: " << endl;

    // DO_4: Write the code to read the expression entered by the user
    // as input on one line.
    // Input order: num1 arithmeticOperator num2
    cin >> num1 >> arithmeticOperator >> num2;
    cout << endl;

    // DO_5: Complete the if condition and corresponding code-block
    // to set isValidNum to true only if both numbers are greater than
    // or equal to 0

    if (isValidNum = true) {
        cin >> num1, num2 >= 0;
    }

    // DO_6: Complete the if condition and corresponding code-block
    // to check whether the expression has valid arithmetic operator
    // such as '+' or '-' and set isValidOperator to true

    if (isValidOperator = true) {
        cin >> arithmeticOperator;
    }

    //DO_7: Print out "Valid expression" if isValidNum is true
    //      and isValidOperator is true

    if (isValidNum == true && isValidOperator == true) {
        cout << "Valid expression" << endl;
    }

    //DO_8: Otherwise, Print "Invalid expression"( use else )

    else {
        cout << "Invalid expression" << endl;
    }

    //DO_9: Calculate and print out the result if the expression is valid
    //      Hint: You need to write two if blocks:
    //            one to calculate and print the result for +
    //            another to calculate and print the result for -

    if (isValidOperator = true) {
        cout <<num1+num2<< endl;
    }

    if (isValidOperator = true) {
        cout <<num1-num2<< endl;
    }

    return 0;
}

1 Answer

+2 votes
answered Oct 2, 2020 by Peter Minarik (86,040 points)

This is C++

Let me start by saying that this is not a C program, this is C++. Well, only because you use the <iostream>, otherwise the rest would run just as fine as a C code. If you really need C and not C++, use <stdio.h> and printf to print on the screen, scanf to read from the standard input.

Problems

"=" means assignment, "==" means comparison

When you want to compare a variable if it is equal to some value, you have to use the "==" (equals) operator, not the "=" (assignment) operator. In C, C++ every assignment will be evaluated to a boolean value: if the variable after the assignment ("=") is zero, the expression evaluates to false; in any non-zero cases it is true.
So the following line are all wrong (assignments, when you should have done comparison):
// ...
if (isValidNum = true)
// ...
if (isValidOperator = true) // this one happens 3 times.
// ...

What did you mean here?

I saw the following code and wasn't sure what you meant to do here:
if (isValidNum = true) {
    cin >> num1, num2 >= 0;
}
So what this does is read num1 from the stdin, then checks if num2 is at least 0, but does not do anything with the result of this check.

Code fixed

I've updated the code so it compiles and runs. The functions that check if the numbers or the operator is valid is not complete, I left it for you to finish. Also, I've left comments in the code with the // PM: prefix so you can see that those comments came from me.
I hope this helps.
#include <iostream>
#include <iomanip>
using namespace std;

static bool IsValidArithmeticOperator(char op)
{
    // PM: Implement the check for a valid arithmetic operator here and modify the return value accordingly.
    //     For now, we'll return true always.
    return true;
}

static bool IsValidNumber(float number)
{
    // PM: Implement the check for a valid floating point number.
    //     Look at the function: atof (http://www.cplusplus.com/reference/cstdlib/atof/) or write your own if you fancy. :)
    //     For now, we'll return true always.
    return true;
}

int main()
{
    cout << fixed << showpoint << setprecision(2);

    // DO_3: Declare the variables required for the expression
    // The expression has two floating point numbers called num1
    // and num2 and a char variable called arithmetic Operator
    // to be used as an operator
    
    // PM: It is useful to only declare at the point where it is needed. Also, when you declare it, initialize (assign a value to) it as well -- if possible.

    // Declare two boolean variables and initialize to false:
    // The first one will indicate whether the number(s) are valid or not,
    // called isValidNum.
    // The second one will indicate whether the operator is valid or not,
    // called isvalidOperator.

    cout << "Enter an arithmetic expression: " << endl;

    // DO_4: Write the code to read the expression entered by the user
    // as input on one line.
    // Input order: num1 arithmeticOperator num2
    float num1, num2;
    char arithmeticOperator;
    cin >> num1 >> arithmeticOperator >> num2;
    cout << endl;
    
    cout << "This is what I read: " << num1 << " " << arithmeticOperator << " " << num2 << endl;

    // DO_5: Complete the if condition and corresponding code-block
    // to set isValidNum to true only if both numbers are greater than
    // or equal to 0
    
    // PM: For now, we set isValidNum to true. Please implement the logic to check if it's a valid numeber. Look at the function: atof (http://www.cplusplus.com/reference/cstdlib/atof/) or write your own if you fancy. :)
    bool isValidNum = false;

    while (!IsValidNumber(num1))
    {
        cout << "Invalid number: " << num1 << endl << "Please, enter a valid number: ";
        cin >> num1;
    }

    while (!IsValidNumber(num2))
    {
        cout << "Invalid number: " << num1 << endl << "Please, enter a valid number: ";
        cin >> num2;
    }
    
    // PM: When we reach this point, we made sure both num1 and num2 are valid floating point numbers.
    // To be fair, isValidNumb at this point is meaningless as it's value can always be true, as the while loop wouldn't allow the use to pass as long as the numebers are not provided. :)
    isValidNum = true;

    // DO_6: Complete the if condition and corresponding code-block
    // to check whether the expression has valid arithmetic operator
    // such as '+' or '-' and set isValidOperator to true

    bool isValidOperator = false;
    
    while (!IsValidArithmeticOperator(arithmeticOperator))
    {
        cout << "Invalid operator: " << arithmeticOperator << endl << "Please, enter a valid operator.";
        cin >> arithmeticOperator;
    }
    
    // PM: Same as above, isValidOperator is always true due to the above while.
    //     If you want to allow the user not to enter valid numbers, just turn the while into an if.
    isValidOperator = true;

    //DO_7: Print out "Valid expression" if isValidNum is true
    //      and isValidOperator is true

    if (isValidNum == true && isValidOperator == true)
    {
        cout << "Valid expression" << endl;
    }

    //DO_8: Otherwise, Print "Invalid expression"( use else )

    else
    {
        cout << "Invalid expression" << endl;
    }

    //DO_9: Calculate and print out the result if the expression is valid
    //      Hint: You need to write two if blocks:
    //            one to calculate and print the result for +
    //            another to calculate and print the result for -
    
    // PM: These instructions make no sense to me. Why would you need two if blocks?!

    if (isValidOperator == true)
    {
        cout << num1 + num2 << endl;
        cout << num1 - num2 << endl;
    }
    
    // PM: I would do something like this for evaluating the operator and the operarands
    //switch (arithmeticOperator)
    //{
    //    case '+':
    //        cout << "num1" << " + " << num2 << " = " << num1 + num2 << endl;
    //        break;
    //
    //    case '-':
    //        cout << "num1" << " - " << num2 << " = " << num1 - num2 << endl;
    //        break;
    //
    //    case '*':
    //        cout << "num1" << " * " << num2 << " = " << num1 * num2 << endl;
    //        break;
    //
    //    case '/':
    //        cout << "num1" << " / " << num2 << " = " << num1 / num2 << endl;
    //        break;
    //
    //    default:
    //        count << "Unsupported operator: " << arithmeticOperator << endl;
    //        break;
    //}

    return 0;
}
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...