Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I was doing an assignment for my subject here and in the assignment, every student is required to create a simple C++ program. The problem here is, when I do not assign a default to a variable, a compile error will occur. However, when I assign a default value (in this case, value = 0), the value will always be 0.
My question is, is there any way to solve this problem while not encountering the compile error?
If there was a similar question asked, could you please also, include the link to the solved question as well? Thank you very much!
[Edit #1: To those who wonder why the code is "messy", I only used simple commands and did not use object oriented components, if/else statements etc. The project created was meant to be composed of "simple codes".]
[Edit #2: This is the output display that I snapped:
http://i.imgur.com/4csk1Rz.png
The Total Discounted fee part should be displaying numbers instead of default value 0]
(Microsoft Visual Studio Pro 2013; C++)
Expected output display:
http://i.imgur.com/jOJvymV.png
#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main()
{
/* Declare variables */
int qtyVehicleCar, qtyVehicleTaxi, qtyVehicleTruck; // User input
double feeOriginalCar, feeTotalOriginalCar, rateDiscountCar, feeTotalDiscountedCar, feeTotalAfterDiscountedCar; // variables for vehicle Car
double feeOriginalTaxi, feeTotalOriginalTaxi, rateDiscountTaxi, feeTotalDiscountedTaxi, feeTotalAfterDiscountedTaxi; // variables for vehicle Taxi
double feeOriginalTruck, feeTotalOriginalTruck, rateDiscountTruck, feeTotalDiscountedTruck, feeTotalAfterDiscountedTruck; // variables for vehicle Truck
double feeRepTotalOriginalFee, feeRepTotalDiscountedFee, feeRepTotalAfterDiscounted; // Generate final output
cout << "=====================================\n";
cout << "=====================================\n";
cout << "====== Malaysia Highway Company =====\n";
cout << "=====================================\n";
cout << "=====================================\n";
cout << endl;
cout << "Enter quantity of the vehicles on 1st January 2014: " << endl;
cout << "Car\t\t:\t";
cin >> qtyVehicleCar;
cout << "Taxi\t\t:\t";
cin >> qtyVehicleTaxi;
cout << "Truck\t\t:\t";
cin >> qtyVehicleTruck;
/* Lay out the Report table */
cout << endl << endl << endl;
cout << "Report\n";
cout << "--------\n";
cout << endl;
/* ============================== */
/* Declaration prior to process */
/* ============================== */
/* The problematic part
feeTotalDiscountedCar = 0;
feeTotalDiscountedTaxi = 0;
feeTotalDiscountedTaxi = 0;
*/
// Prices
feeOriginalCar = 2.00;
feeOriginalTaxi = 1.00;
feeOriginalTruck = 3.50;
feeTotalOriginalCar = feeOriginalCar * qtyVehicleCar;
feeTotalOriginalTaxi = feeOriginalTaxi * qtyVehicleTaxi;
feeTotalOriginalTruck = feeOriginalTruck * qtyVehicleTruck;
// In percentage
rateDiscountCar = 2;
rateDiscountTaxi = 10;
rateDiscountTruck = 15;
feeTotalAfterDiscountedCar = (rateDiscountCar/100) * feeTotalOriginalCar;
feeTotalAfterDiscountedTaxi = (rateDiscountTaxi/100) * feeTotalOriginalTaxi;
feeTotalAfterDiscountedTruck = (rateDiscountTruck/100) * feeTotalOriginalTruck;
// Final total - to be displayed
feeTotalAfterDiscountedCar = feeTotalOriginalCar - feeTotalAfterDiscountedCar;
feeTotalAfterDiscountedTaxi = feeTotalOriginalTaxi - feeTotalAfterDiscountedTaxi;
feeTotalOriginalTruck = feeTotalOriginalTruck - feeTotalAfterDiscountedTruck;
feeRepTotalOriginalFee = feeTotalOriginalCar + feeTotalOriginalTaxi + feeTotalOriginalTruck;
feeRepTotalDiscountedFee = feeTotalDiscountedCar + feeTotalAfterDiscountedTaxi + feeTotalAfterDiscountedTruck;
feeRepTotalAfterDiscounted = feeRepTotalOriginalFee - feeRepTotalDiscountedFee;
/* ================= */
/* Declaration END */
/* ================= */
/* Gives the following variables a default value, they will be modified later by the program */
feeTotalAfterDiscountedTruck = 0;
feeTotalDiscountedTruck = 0;
/* Processes */
cout << "Item\t\t\t\t" << "Car\t" << "Taxi\t" << "Truck\t" << endl;
cout << "------------------------------------------------------\n";
cout << "Original fee\t\t\t" << "RM " << feeOriginalCar << "\t" << "RM " << feeOriginalTaxi << "\t" << "RM " << feeOriginalTruck << endl;
cout << "Quantity\t\t\t" << qtyVehicleCar << "\t" << qtyVehicleTaxi << "\t" << qtyVehicleTruck << endl;
cout << "Total original fee\t\t" << "RM " << feeOriginalCar << "\t" << "RM " << feeOriginalTaxi << "\t" << "RM " << feeOriginalTruck << endl;
cout << "Discount rate\t\t\t" << rateDiscountCar << "%\t" << rateDiscountTaxi << "%\t" << rateDiscountTruck << "%\t" << endl;
cout << "Total discounted fee\t\t" << "RM " << feeTotalDiscountedCar << "\t" << "RM " << feeTotalDiscountedTaxi << "\t" << "RM " << feeTotalDiscountedTruck << endl;
cout << "Total after discounted fee\t" << "RM " << feeTotalAfterDiscountedCar << "\t" << "RM " << feeTotalAfterDiscountedTaxi << "\t" << "RM " << feeTotalAfterDiscountedTruck << endl;
cout << endl;
/* Displays output */
cout << "Total original fee\t\t:\t" << "RM " << feeRepTotalOriginalFee << endl;
cout << "Total discounted fee\t\t:\t" << "RM " << feeRepTotalDiscountedFee << endl;
cout << "Total after discounted fee\t:\t" << "RM " << feeRepTotalAfterDiscounted << endl;
cout << endl << endl;
/* Displays end line */
cout << "------------------- End of Program -------------------" << endl;
system("PAUSE");
return 0;
}
An uninitialized variables warning can mean either (1) you forgot to initialize something or (2) you thought you initialized it but didn't. Looks to me that in this case it's the second problem. Your variable names are mixed up.
For example,
feeTotalAfterDiscountedCar = (rateDiscountCar/100) * feeTotalOriginalCar;
feeTotalAfterDiscountedTaxi = (rateDiscountTaxi/100) * feeTotalOriginalTaxi;
feeTotalAfterDiscountedTruck = (rateDiscountTruck/100) * feeTotalOriginalTruck;
These are supposed to be the amounts of the discounts, no? So why are you storing them into feeTotalAfterDiscountedSomething rather than feeTotalDiscountedSomething?
Similarly,
feeTotalAfterDiscountedCar = feeTotalOriginalCar - feeTotalAfterDiscountedCar;
feeTotalAfterDiscountedTaxi = feeTotalOriginalTaxi - feeTotalAfterDiscountedTaxi;
feeTotalOriginalTruck = feeTotalOriginalTruck - feeTotalAfterDiscountedTruck;
Why is the third one storing the result into feeTotalOriginalTruck instead of feeTotalAfterDiscountedTruck? (Note also that if you fix the first problem above, the rhs of the subtraction will also need to change).
Also,
feeRepTotalDiscountedFee = feeTotalDiscountedCar + feeTotalAfterDiscountedTaxi + feeTotalAfterDiscountedTruck;
Similar problem. These should, I believe, all be feeTotalDiscountedSomething rather than feeTotalAfterDiscountedSomething.
The compiler rightfully complains that feeTotalDiscountedCar and feeTotalDiscountedTaxi are uninitialized. You need to initialize them somewhere. Maybe you want the user to enter them somewhere like this:
cout << "Discount Fee Total Taxi:";
cin >> feeTotalDiscountedTaxi;
cout << "Discount Fee Total Car:";
cin >> feeTotalDiscountedCar;
why are you setting them to zero just before printing out?
feeTotalAfterDiscountedTruck = 0;
feeTotalDiscountedTruck = 0;
It will show the error because you are trying to use the variable with out initializing it.
Related
its a text based monopoly game where i need the dice to select the number from the array like on a board.
I have the number generator, what i need to do though is when the value comes up it pluses it on the array to get the matching number so for example if the players rolls a 6, the 6 + array 0 = array value 6 which will be a name of a street but it means the player knows which place on the made up board they are on. here is the coding i am using to try and do so but i keep on getting 006ff65 what ever. i how can i get it for showing just the number as the names will be added later.
{
int main()
{
int number = 12;
int rnum = (rand() % number) + 1;
int house = 1;
int moneyscore = 10000;
double values[] = {
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40 };
char name[50];
cout << "Who are you, Dog, Car, Hat or Bus" << endl;
cin.getline(name, 50);
cout << "Welcome to Our Game " << name << " You have " << moneyscore << " .PLease Roll dice to get started" << endl;
cout << "\n----------------------Press any Enter to roll dice----------------------" << endl;
system("cls");
int choiceOne_Path;
cout << "# You roll a " << rnum << endl;
rnum = values[rnum];
cout << "# you have " << moneyscore << endl;
cout << "# You move to grid "<< values << endl;
cout << "\t >> Enter '1' Buy Property" << endl;
cout << "\t >> Enter '2' Recieve Rent" << endl;
cout << "\t >> Enter '3' End turn" << endl;
retry:
cout << "\nEnter your choice: ";
cin >> choiceOne_Path;
if (choiceOne_Path == 1)
{
cout << "\n Buy Property " << endl;
cout << " " << name << " has " << moneyscore << endl;
cout << " " << house <<" House has been placed by " << name <<" who spent 2,500" << endl;
moneyscore -= 2500;
cout << " " << name << " now has " << moneyscore << endl;
cout << "\n Roll again" << endl;
cout << "# You roll a " << rnum << endl;
}
else if (choiceOne_Path == 2)
{
cout << "\n You recieved 2500 from rent" << endl;
moneyscore += 2500;
cout << " " << name << "\n now has" << moneyscore << endl;
cout << "\n(Player will gain money form house, will need to find a way in order to make the
console remember what score == to postion)" << endl;
cout << "Ends turn" << endl;
}
else if (choiceOne_Path == 3)
{
cout << "\n Roll again" << endl;
cout << "# You roll a " << rnum << endl;
}
else
{
cout << "You are doing it wrong, player! Press either '1' or '2', nothing else!" << endl;
goto retry;
}
cout << "\n----------------------Press any key to continue----------------------" << endl;
_getch();
}
}
As far as I know, you should use srand (time(NULL)); between every call to rand() to correctly return a new random number from every call.
"srand" initialize the random number generator using a seed. In this case seed is time, which should be different on every call.
Pretty basic. You either made a few typos or need to learn how arrays work (and program flow, and subroutines, but perhaps that is for later lessons.)
First you are assigning the result of the array lookup back into your random number: rnum = values[rnum]; which is not a big deal except you use that variable later and it no longer contains what you may think it does. It actually contains the value you are looking for!
Second the variable values is a pointer to the head of your array so you are outputting the address of the values array with this line: cout << "# You move to grid "<< values << endl; there is no array look up happening at all here. It is strange you missed that because you did reference the array contents properly when you replaced the random number value earlier.
I was able to loop a file that gave me the miles driven, gallons used, and gasoline cost at a certain day successfully. Now I'm trying to figure out how to get the sum of miles driven, gallons used, and gasoline cost by using loops
int main()
{
ifstream inputFile;
int x = 1;
int milesDriven = 0;
double gallonsUsed = 0,
gasolineCost = 0;
int truckNumber,
numberOfTrips,
sumMilesDriven = 0;
double sumGallonsUsed = 0,
sumGasolineCost = 0;
int avgMilesDriven;
double avgGallonsUsed,
avgGasolineCost;
/* Display Truck Information
Get Number of Trips
Get Truck Information
Process Each Trip
Display Averages
*/
inputFile.open("100.txt");
//Display Truck Information
cout << " " << setw(35) << "Red-Rig Trucking" << endl << endl;
cout << " " << setw(40) << "Summary of Truck Operations" << endl << endl;
inputFile >> truckNumber;
cout << "Truck: " << truckNumber << endl << endl;
inputFile.close( );
inputFile.open("truck.txt");
//Get Number of Trips
inputFile >> numberOfTrips;
//Get Truck Information
cout << "Day" << " " <<setw(16) << "Miles" << " " << setw(16) << "Gallons"
<< " " << setw(16) << "Gasoline" << endl << setw(20) << "Driven" << " "
<< setw(16) << "Used" << " " << setw(16) << "Cost" << endl << endl;
while(!inputFile.eof()){
inputFile >> milesDriven >> gallonsUsed >> gasolineCost;
cout << x << " " << setw(17) << milesDriven << " " << setw(17)
<< fixed << setprecision(2) << gallonsUsed << " " << setw(12) << fixed
<< setprecision << gasolineCost << endl ;
x++;
}
//Process Each Trip
/*while(inputFile)
{ sumMilesDriven = sumMilesDriven + milesDriven;
inputFile >> milesDriven;
}*/
for (; milesDriven--;)
sumMilesDriven += milesDriven;
cout << endl << "Sum" << " " << setw(15) << sumMilesDriven ;
for (;gallonsUsed;)
sumGallonsUsed += gallonsUsed;
cout << " " << setw(17) << sumGallonsUsed;
for (;gasolineCost--;)
sumGasolineCost += gasolineCost;
inputFile.close( );
return 0;
}
I've gotten this far and I can't figure out what's wrong. I've taken out the milesDriven >=10 from the for loop parenthesis. When the code runs I get an incorrect sum amount. The sum is either too big or too small.
Your code:
for (sumGasolineCost += gasolineCost; gasolineCost >= 1; gasolineCost--);{
cout << " " << setw(17) << sumGasolineCost;
}
My first advice is, do not write confusing code. Whenever you're programming, you have better things to do than tie your shoelaces together. I think you know the above is equivalent to:
for (sumGasolineCost += gasolineCost; gasolineCost >= 1; gasolineCost--);
cout << " " << setw(17) << sumGasolineCost;
That lets us discuss the loop itself. Go back and consult your textbook. The for loop has three components:
for( init ; test ; incr )
init is executed once, usually to initialize what will be tested
test is executed on each iteration, including the first, to determine if the loop body will be executed
incr is executed after the loop body, usually to update the tested value
In your case, sumGasolineCost += gasolineCost is in init. It is executed once. It should be in the loop body. There are other errors, too. I can't be much more specific because you don't indicate where the array or input is that you're looping over.
Once you get your loop doing what it should, you might find the standard std::accumulate function interesting to compare to.
So this program is supposed to collect weather temperatures over 7 days using a for loop and then basically just print them back out to the user with an average temperature and the highest recorded temperature. Keep in mind, the following piece of code is a part of a much larger program. Anyway, the problem seems to be the "highest_temp1" float variable. When I run the program it produces some sort of error code instead of the highest temperature. This piece of code was tested in a separate source file and it works no problem.
switch (choice)
{
case 3:
int n;
float temperatures [7];
float lastweektemp [7] = {12.56,8.65,7.5,10,7.9,5,8};
float highest_temp1, highest_temp2;
float accumulated_temp1, accumulated_temp2;
system("CLS");
cout << "____________Weather Data____________" << endl << endl;
for (n = 0; n<7; n++)
{
cout << "What is the temperature for Day " << n+1 << " ?" << endl;
cin >> temperatures[n];
if (highest_temp1 < temperatures [n])
{
highest_temp1 = temperatures [n];
}
if (highest_temp2 < lastweektemp [n])
{
highest_temp2 = lastweektemp [n];
}
accumulated_temp1 = accumulated_temp1 + temperatures[n];
accumulated_temp2 = accumulated_temp2 + lastweektemp [n];
}
cout << endl << " Day This Week Last Week" << endl;
for (n=0; n<7; n++)
{
cout << n+1 << temperatures[n] << lastweektemp[n] << endl;
}
system("CLS");
cout << " Weather Report" << endl;
cout << " --------------" << endl << endl;
cout << "Current Week: " << endl;
cout << "-------------" << endl;
for (n=0; n<7; n++)
{
cout << "Day " << n+1 << ": " << temperatures[n] << endl;
}
cout << endl << " Average: " << accumulated_temp1 / 7 << endl;
cout << " Highest Temperature: " << highest_temp1 << endl;
cout << "Last Week: " << endl;
cout << "----------" << endl;
for (n=0; n<7; n++)
{
cout << "Day " << n+1 << ": " << lastweektemp[n] << endl;
}
cout << endl << " Average: " << accumulated_temp2 / 7 << endl;
cout << " Highest Temperature: " << highest_temp2 << endl;
system("PAUSE");
}
The highest temperature in current week is 24 but it is printing "Highest Temperature: 3.45857e+032"
This exact 'error-code' is appearing every time I run the program it doesn't change.
I am a newbie hence why I can't upload a photo.
Any help would be appreciated. I'm doing a small assignment in college. This is my first question so go easy !!
You have not assigned any value to teh variable highest_temp1 and you are comparing it with another value.
Basically you will need to assign it a value first before you compare..
highest_temp1 = 10.00
(or anything that it is supposed to contain)
You have not initialised highest_temp1 (or highest_temp1 for that matter: after that I stopped looking).
Same for accumulated_temp, which gets not initialised. can be done via
float accumulated_temp1(0);
Initialize variables before using them
float highest_temp1(-FLT_MAX); // -FLT_MAX insures results of first compare
float highest_temp2(-FLT_MAX); // Could use -1.0/0.0 of -INFINITY instead
float accumulated_temp1(0.0);
float accumulated_temp2(0.0);
For float number condition use if statements switch is not able to work in case of float number, switch only work for integer number.
I'm trying to print out the contents of my array, however it also prints the memory address of each element, then prints the element.
void generateEndOfDayReport(taxiDetails taxiDataStore[], fareDetails reportArray[])
for (int i = 0; i < 14; i++)
{ cout << "Here is a list of the taxi drivers in ascending last name order: " <<
cout << taxiDataStore[i].taxiDriverSurname << endl << "And here is the money they took in over the course of today: £" << taxiDataStore[i].fareDetailsForTaxi.overAllFareDetails << endl << endl;
}![enter image description here][1]
By the look of your code, you've got a typo, it reads:
cout << some-text << cout << variable << endl << some-more-text << variable << endl << endl;
Note that you are streaming cout into cout. Is that really what you intended?
I am having a couple problems with my code.
First off, with the code like it is, No matter what information I put in, It always returns 0, Any suggestions on where to fix this and how? I believe it has something to do with my Class Employee. How would I go about fixing this?
Second, How do I access the information in int total()? I need to access it for the last bit of code.
Also if you notice anything else that I can do to optimize my program, I welcome your suggestions. I am learning C++ as I go and will always be a Student.
// Datamax.cpp
// Created by Kennith Adkins
#include <iostream>
#include <string>
using namespace std;
class Employee
{
public:
string eName;
float eHours;
float eWage;
float ePay;
float eOvertimeHours;
float eOvertimePay;
float eTotalPay;
float eTotalBaseHours;
float eTotalSalary;
float eTotalOvertimeHours;
int Overtime ()
{
if (eHours > 40)
{
eOvertimeHours = (eHours - 40);
eOvertimePay = (eOvertimeHours * (eWage * 1.5));
ePay = ((eHours - eOvertimeHours) * eWage);
eTotalPay = ePay + eOvertimePay;
}
else
{
ePay = (eHours * eWage);
}
}
int total()
{
eTotalBaseHours = (employee1.eHours - employee1.eOvertimeHours) + (employee2.eHours - employee2.eOvertimeHours) + (employee3.eHours - employee3.eOvertimeHours);
eTotalSalary = (employee1.eTotalPay + employee2.eTotalPay + employee3.eTotalPay);
eTotalOvertimeHours = (employee1.eOvertimeHours + employee2.eOvertimeHours + employee3.eOvertimeHours);
}
} employee1, employee2, employee3;
// Start the main program here
int main()
{
// Gretting
cout << "Welcome to the Employee Pay Center\n";
// Employee1 information
cout << "Enter the employee name: ";
cin >> employee1.eName;
cout << "Enter the hours worked: ";
cin >> employee1.eHours;
cout << "Enter his or her hourly wage: ";
cin >> employee1.eWage;
cout << endl; // Adding a blank line to space the information out
// Employee2 information
cout << "Enter the employee name: ";
cin >> employee2.eName;
cout << "Enter the hours worked: ";
cin >> employee2.eHours;
cout << "Enter his or her hourly wage: ";
cin >> employee2.eWage;
cout << endl; // Adding a blank line to space the information out
// Employee3 information
cout << "Enter the employee name: ";
cin >> employee3.eName;
cout << "Enter the hours worked: ";
cin >> employee3.eHours;
cout << "Enter his or her hourly wage: ";
cin >> employee3.eWage;
cout << endl; // Adding a blank line to space the information out
// Returning the information to the Employeer
cout << "Employe Name ............ = " << employee1.eName << "\n";
cout << "Base Pay................. = " << employee1.ePay << "\n";
cout << "Hours in Overtime........ = " << employee1.eOvertimeHours << "\n";
cout << "Overtime Pay Amount...... = " << employee1.eOvertimePay << "\n";
cout << "Total Pay................ = " << employee1.eTotalPay << "\n\n";
cout << "Employe Name ............ = " << employee2.eName << "\n";
cout << "Base Pay................. = " << employee2.ePay << "\n";
cout << "Hours in Overtime........ = " << employee2.eOvertimeHours << "\n";
cout << "Overtime Pay Amount...... = " << employee2.eOvertimePay << "\n";
cout << "Total Pay................ = " << employee2.eTotalPay << "\n\n";
cout << "Employe Name ............ = " << employee3.eName << "\n";
cout << "Base Pay................. = " << employee3.ePay << "\n";
cout << "Hours in Overtime........ = " << employee3.eOvertimeHours << "\n";
cout << "Overtime Pay Amount...... = " << employee3.eOvertimePay << "\n";
cout << "Total Pay................ = " << employee3.eTotalPay << "\n\n";
cout << "*******************************************************\n";
cout << "*****************EMPLOYEE SUMMARY DATA*****************\n";
cout << "*******************************************************\n";
cout << "** Total Employee Salaries............ " << "**\n";
cout << "** Total Employee Hours............... " << "**\n";
cout << "** Total Overtime Hours............... " << "**\n";
cout << "*******************************************************\n";
cout << "*******************************************************\n";
return 0;
}
Hey Guys, Thanks for the help. I have most of it done now. It is displaying all the information. I am now just working on getting it to display the Employee Summary Data. I revamped my code to make it cleaner because I was trying every suggestion given to me as I learn best by hands on.
That's what you get for using non-initialized variables. You have set no value to your class members, you can't expect the compiler to guess what is your employee's name or total pay.
You need to use the form:
object name.member name = value
Of course, you should call the functions before outputting results that are supposed to be produced by these functions:
employee1.Overtime();
employee2.Overtime();
employee3.Overtime();