I am new to C++, I wrote this code for practice and can't seem to understand why my code still loops after I input the sentinel value.
Sample output: Please enter your sales amount or -1 to exit: 25100 Your salary for the month is:$31110.00 Please enter your sales amount or -1 to exit: -1 Your salary for the month is:$3499.00 –
Here is my code:
#include <stdio.h>
#include <math.h>
#define MIN 25000
#define COMP .10
#define BASPAY 3500
//Function Prototypes
double MonthSales(void);
double CalcPay(double sales);
//Begin Main
int main(void)
{
//declare variables
double sales = 0;
// Begin Program with sentinel value for exit
while (sales != -1)
{
sales = MonthSales();
printf("Your salary for the month is:$%.2lf\n", CalcPay(sales));
//The line above still runs after I input -1 :S.
}
}
//Function for sales
double MonthSales(void)
{
double sales;
printf("Please enter your sales amount or -1 to exit:\n");
scanf("%lf", &sales);
return sales;
}
//Function for total Pay
double CalcPay(double sales)
{
double pay;
double commission;
if (sales > MIN)
{
commission = sales * COMP;
pay = commission + sales + BASPAY;
}
else
{
pay = sales + BASPAY;
}
return pay;
}
In this loop:
while (sales != -1)
{
sales = MonthSales();
printf("Your salary for the month is:$%.2lf\n", CalcPay(sales));
}
the control expression sales != -1
is evaluated before each iteration of the loop. It is not evaluated continuously or at points inside the iterations. The loop does not automatically stop the moment sales != -1
becomes false.
Instead, you must test the value of sales
at the point where you want the control flow to change. For example, you can do this:
while (1)
{
sales = MonthSales();
if (sales == -1)
break;
printf("Your salary for the month is:$%.2lf\n", CalcPay(sales));
}