jeudi 25 octobre 2018

The if statements' condition

In exercise ten of chapter 3 in this book im trying to go over, I was asked to write a program that takes an operation followed by two operands and output the results. Read the operation into a string called operations and use an if-statement to figure out which operation the user wants.Read the operands into variables of type double. Implement this for operations called +,-,*,/, you know (plus, minus, multiplication, division) the obvious.

This is what I wrote so far and it worked and all but my issues is the concept of the condition in the if-statements. From what I understand the if statement has parenthesis, that within are the conditions where the values are tested to see if they are true or false, Only after that the computer decided whether to run the code or not. So tell me why do I have to write the operation equal to the operator as the conditions, when I have to use the operator in the cout to get the results of the two input values anyway ? I don't understand this, isn't there a better way of writing this with less statements ?

#include "stdafx.h"
#include "iostream"
#include "string"

using namespace std;

int main()
{
    string operation = "";
    double operands1;
    double operands2;
    cout << "Give me either a minus, plus, division, or multiplication operations \n";
    cin >> operation;
    cout << " enter the value you would like to  \n";
    cin >> operands1;
    cout << " enter the second value you would like to \n";
    cin >> operands2;

    if (operation == "+")// I was told to write it like this in the book  {
        cout << operands1 + operands2 << endl;
    }
    else if (operation == "*") {
        cout << operands1*operands2 << endl;
    }
    else if (operation == "-") {
        cout << operands1 - operands2 << endl;
    }
    else if (operation == "/") {
        cout << operands1 / operands2 << endl;
    }
    else {
        cout << " seriously dude im talking about numbers over here \n";
    }
    return 0;
}

Aucun commentaire:

Enregistrer un commentaire