Velocity Reviews > C++ > C++ Salary Array

# C++ Salary Array

Ian Collins
Guest
Posts: n/a

 10-08-2012
On 10/09/12 10:09, James Strickland wrote:
> <SNIP>
>
>> This works correctly only in the first iteration, when salary still
>>
>> equals 200; the salary computed in, say, the second iteration,
>>
>> will be the sum of the first salary and the second commission,
>>
>> while it should be the sum of 200 and the second commission.

>
> Ok, I'm not sure how to tackle that... should salary be a constant, would that fix it?

Something like

outside the loop:

const int baseSalary = 200;

inside the loop:

int commission = grossSales * .09;
int salary = baseSalary + commission;

Note the variables are declared where they belong inside the loop.

--
Ian Collins

Ike Naar
Guest
Posts: n/a

 10-08-2012
On 2012-10-08, James Strickland <(E-Mail Removed)> wrote:
><SNIP>
>
>> This works correctly only in the first iteration, when salary still
>>
>> equals 200; the salary computed in, say, the second iteration,
>>
>> will be the sum of the first salary and the second commission,
>>
>> while it should be the sum of 200 and the second commission.

>
> Ok, I'm not sure how to tackle that... should salary be a constant, would that fix it?

If salary is a constant, it cannot be changed after initialization.
The simplest way is probaby to use the proper values in the
computation of salary inside the loop:

int salary = 200;
int commission = 0;
/* ... */
while (grossSales != -1)
{
commission = grossSales * 0.09;
salary = 200 + commission;
if (salary >= 200 && salary <= 299)
/* ... */
}

If you want to use a named constant for the \$200 base salary,
which would probably be a good idea, you could do something like

const int baseSalary = 200;
int salary = 200;
int commission = 0;
/* ... */
while (grossSales != -1)
{
commission = grossSales * 0.09;
salary = baseSalary + commission;
if (salary >= 200 && salary <= 299)
/* ... */
}

Note that commission and salary are never used outside the loop,
except for initializing them with some meaningless value.
You could move them inside the loop, and initialize them
with meaningful values:

const int baseSalary = 200;
/* ... */
while (grossSales != -1)
{
int commission = grossSales * 0.09;
int salary = baseSalary + commission;
if (salary >= 200 && salary <= 299)
/* ... */
}

and now they could even be made constant:

const int baseSalary = 200;
/* ... */
while (grossSales != -1)
{
const int commission = grossSales * 0.09;
const int salary = baseSalary + commission;
if (salary >= 200 && salary <= 299)
/* ... */
}