0
//#include conio.h   
//#include iomanip    
//#include iostream    
//#include string    

using namespace std;

const string Zo;
double Sp;
double Li;
double Ti;

void main()
{
    cout<<setiosflags(ios::fixed);
    cout<<setprecision (2);
    cout<<setw(22)<<"Speeding Ticket"<<endl;
    cout<<"Please Enter Your Speed :";
    cin>>Sp;
    cout<<"Speed Limit:";
    cin>>Li;
    cout<<"IF School Zone Enter (Yes/No):";
    cin>>"Yes"||"No";

    if(Zo=="Yes")
        Ti=30+6*(Sp-Li);
    else  
        Ti=30+3*(Sp-Li);
    if (Sp>=Li+30)
        Ti=Ti+100;

    cout<<"Your Speeding Ticket Is:"<<"$"<<Ti<<endl;
    getch();
}

This wasn't my first trial on the first one it was cin>>Zo but the teacher said find a better way so if the user input is wrong it would know. I am a beginner so I did as simply as I could.

4

3 回答 3

1

I suppose your teacher wants better math (which implies better logic our your app), one of possible variants is:

const double additionalTicket = (Sp >= Li+30) ? 100 : 0;
const double schoolZoneMultiplier = (Zo == "Yes") ? 6 : 3; // be sure that you understand when to use strcmp and when ==
Ti = 30 + schoolZoneMultiplier*(Sp-Li) + additionalTicket;

this variant do the same, but you see actual formula, so usually such code is better for understanding, also parts of this code can be executed in parallel by CPU

NOTE: you have problem with cin>>"Yes"||"No"; - this just doesn't make sense

于 2013-10-23T00:17:38.930 回答
0

Using the ternary operator is not better math, just different syntax that can make the code look better (or worse if not used wisely).

This previous post shows that it indeed does not bring any performance improvement.

Ternary operator ?: vs if...else

(Sorry can't put that as a comment yet)

于 2013-10-23T01:29:47.137 回答
0

@vincentB (sorry I can`t comment directly on their post due to my rep)

The ternary operator can be more efficient than an if-else in terms of branchless code produced by the compiler

http://www.altdevblogaday.com/2012/04/10/cc-low-level-curriculum-part-7-more-conditionals/

于 2013-10-23T02:33:19.900 回答