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.
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'm trying to complete an assignment but I'm having difficulty with the math expressions and variables in general. I'm trying to make a program that takes user info on groceries and then outputs a receipt. Here is my code.
#include <iostream>
#include <string>
using namespace std;
int main()
{
//user input
string firstItem, secondItem;
float firstPrice, secondPrice;
int firstCount, secondCount;
double salesTax = 0.08675;
double firstExt = firstPrice * firstCount;
double secondExt = secondPrice * secondCount;
double subTotal = firstExt + secondExt;
double tax = subTotal * salesTax;
double total = tax + subTotal;
//user input
cout << "What is the first item you are buying?" << endl;
getline(cin, firstItem);
cout << "What is the price of the " << firstItem << "?" << endl;
cin >> firstPrice;
cout << "How many " << firstItem << "s?" <<endl;
cin >> firstCount;
cin.ignore();
cout << "What is the second item you are buying?" << endl;
getline(cin, secondItem);
cout << "what is the price of the " << secondItem << "?" << endl;
cin >> secondPrice;
cout << "How many " << secondItem << "s?" << endl;
cin >> secondCount;
// receipt output
cout << "1st extended price: " << firstExt << endl;
cout << "2nd extended price: " << secondExt << endl;
cout << "subtotal: " << subTotal << endl;
cout << "tax: " << tax << endl;
cout << "total: " << total << endl;
return 0;
}
The program output either 0 for all or negatives.
Your calculations must go after you read in the values, not before. You're making your calculations based on uninitialized variables.
A declaration and initialisation like
double firstExt = firstPrice * firstCount;
initialises firstExt to be the product of the current values AT THAT POINT of firstPrice and firstCount.
It doesn't set up some magic so that the value of firstExt is recalculated whenever the values of firstPrice or firstCount are changed.
In your case, firstPrice and firstCount are uninitialised variables when you do this. Accessing values of uninitialised variables of type int gives undefined behaviour.
What you need to do is something like
cout << "What is the price of the " << firstItem << "?" << endl;
cin >> firstPrice;
cout << "How many " << firstItem << "s?" <<endl;
cin >> firstCount;
firstExt = firstPrice*firstCount; // do the calculation here
If the value of firstExt is not needed until this point, you can declare it here instead;
double firstExt = firstPrice*firstCount; // do the calculation here
which means any earlier use of firstExt will give a compiler diagnostic.
I was reading the chapter on structures in my book, and it got me re-modifying a program I already made, but this time using structures which I have never used before; however, after finishing the program, there's one issue I'm not understanding. The output of the program only displays once. It's in a for loop, and yet even though it asks me to input my information three times, it only outputs the first information.
I'm probably just not understanding how arrays in structures work.
An example of my issue is the following.
I have my output on the following loop
for(int counter = 0; counter <size; counter++)
The size is 3, which would mean I'll get the output printed three times; however the answer I'm getting is the same as if I was asking for the following.
Listofnames[0].F_name
When what I actually want is
Listofnames[0].F_name Listofnames[1].F_name Listofnames[2].F_name
However, I don't want to have to write it three times, I did to test it and it actually worked, but is that the only way to do it? Or did I miss something in my program?
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
struct Names
{
string F_name; //Creating structure called Names.
string L_name;
char Mi;
};
struct Payrate
{
double rate;
double hoursworked; //Creating structure called Payrate.
double gross;
double net;
};
int main()
{
double stateTax = 0, federalTax = 0, unionFees = 0, timeHalf = 1.5; //Initializing variables.
const int size = 2; //Array size.
Payrate employee[size]; //Structure variables
Names Listofnames[size];
for (int counter = 0; counter < size; counter++) //Initializing for loop.
{
cout << "What's your first name?: " << endl;
cin >> Listofnames[counter].F_name;
cout << "What's your last name?: " << endl; //Displaying names, and hours worked, rate.
cin >> Listofnames[counter].L_name;
cout << "What is your middle initial?: " << endl;
cin >> Listofnames[counter].Mi;
cout << "How many hours did you work? Please enter a number between 1-50: " << endl;
cin >> employee[counter].hoursworked;
cout << "What is your hourly rate? Please enter a number between 1-50: " << endl;
cin >> employee[counter].rate;
if (employee[counter].hoursworked < 0 || employee[counter].hoursworked >50) //Initializing conditional statements.
{
cout << "Sorry you entered a erong entry. Pc shutting off " << endl; //Displays what happens is user inputs a number under 0 or over 50.
}
if (employee[counter].rate < 0 || employee[counter].rate > 50) //Initializing conditional statements.
{
cout << "Sorry you entered a erong entry. Pc shutting off " << endl; //Displays what happens is user inputs a number under 0 or over 50.
}
if (employee[counter].hoursworked <= 40) //Initializing conditional statements.
{
employee[counter].gross = employee[counter].hoursworked * employee[counter].rate; //Calculating gross.
}
else if (employee[counter].hoursworked > 40) //Initializing conditional statements.
{
employee[counter].gross = employee[counter].hoursworked * (employee[counter].rate * timeHalf); //Calculating gross.
}
stateTax = employee[counter].gross * 0.06;
federalTax = employee[counter].gross * 0.12; //Calculates all the tax fees, and net.
unionFees = employee[counter].gross * 0.02;
employee[counter].net = employee[counter].gross - (stateTax + federalTax + unionFees);
}
cout << "FirstN " << "MI " << "LastName " << "\t" << "Rate " << "HoursWorked " << "TimeHalf " << "StateTax " << "FederalTax " << "UnionFees " << "Gross " << " " << "Net " << endl; //Displays header of output.
cout << "==================================================================================================================" << endl;
for (int counter = 0; counter <= size; counter++)
{
//Output.
cout << Listofnames[counter].F_name << "\t" << fixed << setprecision(2) << Listofnames[counter].Mi << " " << Listofnames[counter].L_name << "\t" << employee[counter].rate << "\t" << employee[counter].hoursworked << "\t" << setw(7) << timeHalf << "\t" << setw(8) << stateTax << setw(12) << federalTax << "\t" << unionFees << "\t" << employee[counter].gross << "\t" << employee[counter].net << endl;
system("pause");
}
}
P.s If you had to re modify this program again, what would you use to simplify it. Asking so I can keep re-modifying, and learn more advanced stuff. Vectors, pointers? Thanks in advance.
You have an array with 3 indexes but your loop is only going upto 2 indexes. Change your for loop to this.
for (int counter = 0; counter <= size; counter++)
Now, this loop will print the all the indexes.
Instead of using a static value you can also use this.
for (int counter = 0; counter < sizeof(Listofnames)/sizeof(Listofnames[0]); counter++)
sizeof(Listofnames)/sizeof(Listofnames[0]) This will give you the total size of your array.
Ideone Link
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.
(Yes this WAS homework, but already completed, I'm just trying to improve it now for practice)
This is basically a sales calculator, that allows you to have multiple inputs for sales items, then displays the total, sales tax, and grand total.
The modification I'm trying to make, is that I want to be able to SAVE the cost of each number of items in a variable, without them overlapping memory, and then be able to call them above the grand total, so you can see what each item was worth.
===========================================================================
//importing libraries for cin and cout, as well as setw() and setprecision()
#include <iostream>
#include <iomanip>
using namespace std; //sets all code to standard syntax
int main(){ //initializes the main function
//initializing variables
char answer = ' ';
int saleItems = 0;
double saleTax = 0.0;
double grandTotal = 0.0;
double itemValue = 0.0;
double titemValue = 0.0;
double taxPerc = 0.0;
//begins a post-test loop
do {
titemValue = 0.0; //makes sure the accumulator resets WITHIN the loop
//prompts for sale items amount
cout << "How many sales items do you have? : ";
cin >> saleItems;
//creates a loop that displays the prompt for each iteration of saleItems
for (int x = 1; x <= saleItems; x += 1){
cout << "Enter in the value of sales item " << x << " : $";
cin >> itemValue;
titemValue += itemValue; //accumulator for adding up the iterated values
}
//prompts the user to enter a sales percentage
cout << endl << endl;
cout << "Enter in the sales tax percentage(Enter 10 for 10%): ";
cin >> taxPerc;
cout << endl << endl;
//processes the variables after taxPerc has been given
saleTax = titemValue * (taxPerc / 100);
grandTotal = titemValue + saleTax;
//sets decimal precision to 2 places
cout << fixed << setprecision(2);
//displays receipt with the calculated and input values
cout << "********************************************" << endl;
cout << "******** S A L E S R E C E I P T ********" << endl;
cout << "********************************************" << endl;
cout << "** **" << endl;
cout << "** **" << endl;
cout << "** **" << endl;
cout << "** **" << endl;
cout << "** Total Sales $" << setw(9) << titemValue << " **" << endl;
cout << "** Sales Tax $" << setw(9) << saleTax << " **" << endl;
cout << "** ---------- **" << endl;
cout << "** Grand Total $" << setw(9) << grandTotal << " **" << endl;
cout << "** **" << endl;
cout << "** **" << endl;
cout << "********************************************" << endl << endl << endl;
//prompts user to begin loop again
cout << "Do you want to run this program again? (Y/N):";
cin >> answer;
answer = toupper(answer);
cout << endl << endl;
} while (answer == 'Y');
===========================================================================
So, essentially, I need to be able to save each itemValue to multiple different values without the loop repeating itself, and just replacing them, and I can't really see how I can do that considering the accumulator will just keep looping, and adding up the itemValue values.
Here is one way to use an simple array to store the item values.
Declare an array at the top. Note: you will have to give it a fixed size. There are ways to have a variable size, but they get more complex (such as vectors). It is better to specify the size using a constant, rather than a hard coded number, as you will need the constant later.
const int maxSaleItems = 100;
double itemValues[maxSaleItems];
After you have asked the user for the number of items, max sure they haven't entered a number that is too big.
cout << "How many sales items do you have? : ";
cin >> saleItems;
if (saleItems > maxSaleItems) {
cout << "Sorry, I can only handle " << maxSaleItems << " items.";
continue;
}
Inside the loop where you are inputting the item values, save the item value to the array:
cout << "Enter in the value of sales item " << x << " : $";
cin >> itemValue;
titemValue += itemValue; //accumulator for adding up the iterated values
itemValues[x - 1] = itemValue;
Note the x-1 in the array access - arrays are 0 based (i.e. their index starts from 0). Normally I would loop x from 0 to < saleItems, but I didn't want to change your existing loop.
When printing the receipt, add a loop which prints out all the values (you will need to add formatting):
cout << "** **" << endl;
for (int x = 1; x <= saleItems; x += 1){
cout << "** Item " << x << " $" << itemValues[x-1] << " **" <<endl;
}
cout << "** **" << endl;
As I said in the comments, using std::vector would be better, but if you aren't up to that yet, arrays will do.
Edit: Simple vector example.
To add vectors you need to include the appropriate header:
#include <vector>
No need for maxSaleItems any more, as vectors can grow. Declare the vector variable. The <double> makes it a vector that contains double values:
std::vector<double> itemValues;
Inside the loop, instead of setting the array value for the new item by location, just add it to the end of the vector using push_back.
cout << "Enter in the value of sales item " << x << " : $";
cin >> itemValue;
titemValue += itemValue; //accumulator for adding up the iterated values
itemValues.push_back(itemValue);
The printing receipt code, can be left exactly as it was for the array version, as you can access vectors like arrays:
cout << "** **" << endl;
for (int x = 1; x <= saleItems; x += 1){
cout << "** Item " << x << " $" << itemValues[x-1] << " **" <<endl;
}
cout << "** **" << endl;
There are other changes you could do to make the vector version simpler, but I wanted to change as little as possible.