Problema operatori

Intrebari despre limbajul C++, standardul C++, STL, OOP in C++ sau alte subiecte nelegate de VisualC++
Post Reply
mkiopl
Junior
Junior
Posts: 1
Joined: 27 Apr 2015, 23:45
Judet: Bucureşti

Problema operatori

Post by mkiopl » 28 Apr 2015, 00:01

Salutare !

Invat de pe cartea lui Stroustrup, "Programming principle and practice" 2nd edition.
M-am blocat la un exercitiu. Defapt, ca sa fiu inteles, in loc sa imi dea 8/0 = 0 , mie imi da 8/0 = 4, si nu inteleg de ce.
Voi posta cerinta, si exercitiul meu.


Cerinta :
10 Write a program that takes an operation followed by two operands and outputs the result. For
example:
+ 100 3.14
* 4 5
Read the operation into a string called operation and use an if-statement to figure out which
operation the user wants, for example, if (operation=="+"). Read the operands into variables
of type double. Implement this for operations called +, –, *, /, plus, minus, mul, and div with
their obvious meanings.








Exercitiul meu :

Code: Select all

#include <iostream>
using namespace std;
int main()
{
    string operation;
    double val1,val2;
    cout<<"Please enter an operation(+,-,*,/,plus,minus,mul,div) followed by two floating-point values separated by a space: ";


        while(cin>>operation>>val1>>val2)       {

                    double res;

            if(operation == "plus" || operation=="+")  res=val1+val2;
       else if(operation == "minus"|| operation=="-")  res=val1-val2;
       else if(operation == "mul"  || operation=="*")  res=val1*val2;
       else if(operation == "div"  || operation=="/")   {

                    if(val2==0)
                        {

                        cout<<"Error! Trying to divide by zero!";

                        }

                    else{
                    res=val1/val2;}
                                                        }

        cout<<val1<<operation<<val2<<"=="<<res<<endl;
        cout<<"please try again"; }
        cout<<"exit cuz of bad input";
}

Va multumesc anticipat pentru toate raspunsurile pe care le voi primi :whorship:



User avatar
bu7ch3r
Membru++
Membru++
Posts: 326
Joined: 17 May 2011, 15:17
Judet: Iaşi
Location: Sofia
Contact:

Re: Problema operatori

Post by bu7ch3r » 28 Apr 2015, 14:29

8/0 tre sa-ti dea eroare, pentru ca nu poti sa imparti cu 0. De asta ai pus acolo if-ul ala in care afisezi "Error! Trying to divide by zero!"

Codul tau merge aproape bine. In caz de eroare trebuie sa te opresti; pune un break dupa eroare.
Ai uitat sa tratezi cazul in care utilizatorul nu introduce corect datele. Dupa toate else if-urile alea iti mai trebuie un else in care sa spui utilizatorului sa introduca datele corect(apoi ori pui break si te opresti cu programul, ori pui continue si o iei de la capat pana pune cineva datele corect).

programul tau:
http://ideone.com/gQe5Zp

niste modificari:
http://ideone.com/ORMhbd
Cu stima,
Lupu Claudiu

Post Reply