Baps
Baps

Reputation: 1

Trying to add while loop to this codeblock

SOLVED 11/19/2017 @ 10:20PM

This is the codeblock I'm working on, and I need to implement a while loop to run it infinitely until the user is satisfied. I'm not sure if gross_pay should be in the condition or if something else needs to be there. I keep on getting this error code. (error C4700: uninitialized local variable 'gross_pay' used)

// GrossPay.cpp : Defines the entry point for the console application.
//int temp = 0;
    #include "stdafx.h"
    #include <iostream>
    #include <stdio.h>
    #include <stdlib.h>
    using namespace std;

        int main()
        {
            double hourly_rate;
            double hours;
        double gross_pay;
        while ( gross_pay >= 1 ) {
        printf("Please input the hourly rate of the employee: ");
        cin >> hourly_rate;
        printf("Please input the number of hours worked by the employee: ");
        cin >> hours;

        if (hours <= 40)
        {
            gross_pay = hours * hourly_rate;
        }
        else
        {
            gross_pay = (40 * hourly_rate) + (hours - 40) * (hourly_rate * 1.5);
        }

        cout << "The gross pay of this employee is $" << gross_pay << "." << endl;

        system("pause");
        return 0;
    }

}

Solution:

// GrossPay.cpp : Defines the entry point for the console application.
#include "stdafx.h"
#include <iostream>
using namespace std;

int main()
{
    double hourly_rate;
    double hours;
    double gross_pay = 1;
    while (gross_pay >= 1) {
        printf("Please input the hourly rate of the employee: ");
        cin >> hourly_rate;
        printf("Please input the number of hours worked by the employee: ");
        cin >> hours;

        if (hours <= 40)
         {
             gross_pay = hours * hourly_rate;
         }
         else
         {
            gross_pay = (40 * hourly_rate) + (hours - 40) * (hourly_rate * 
1.5);
        }

        cout << "The gross pay of this employee is $" << gross_pay << "." << 
endl;


    }
    return 0;
}

Upvotes: 0

Views: 32

Answers (2)

kzharas210
kzharas210

Reputation: 500

The error message says everything, you have to initialize gross_pay first, otherwise its value is undefined

double gross_pay = 1;

Or you can change while loop to do-while

do {
    printf("Please input the hourly rate of the employee: ");
    cin >> hourly_rate;
    .....
    .........
} while ( gross_pay >= 1 );

Upvotes: 0

Sandeep P Pillai
Sandeep P Pillai

Reputation: 743

Every variable should be initialized before you are using for an operation otherwise the result may not be same as you expected.

Rewrite as double gross_pay = 1;

If you don't specify an initialization value then the value for double gross_pay is undefined. It will set to 0 for global variable.

Upvotes: 2

Related Questions