trying to make my first post right so here goes.
I ran into this question and have not been able to figure it out. I keep receiving the error:
error C4700: uninitialized local variable 'miles' used
I have scavenged over all of StackOverflow and keep running into the same answer: I have to initialize my local variable, but when I do that I am creating a set value. I want to set my local variable 'miles' to an unknown value because I want the user to be able to set the value when the program runs.
Everything ran great until I tried to cast the end value 'miles'so that it would truncate.
Please correct me if I'm using incorrect terminology. Fresh-out-of-the-womb-to-programming. And thank you to everyone in advance.
Question:
Write a program that prompts the capacity, in gallons, of an automobile fuel tank and the miles per gallon the automobile can be driven. The program outputs the number of miles the automobile can be driven without refueling. Numbers entered for capacity must allow entry of capacity being an integer and the miles per gallon in decimals. The number of miles must be output to the next lowest integer (without decimals).
#include "stdafx.h"
//include statement
#include<iostream>
//include namespace statement
using namespace std;
//main function
int main()
{
//variable declaration
double capacity_Gallons;
double miles_Gallon;
double miles = static_cast<int>(miles < 0 ? miles - 0.5 : miles + 0.5);
//inputting capacity of automobile
cout << "Enter the capacity of the automobile fuel in gallons: ";
cin >> capacity_Gallons;
cout << endl;
//inputting the miles per Gallons
cout << "Enter the miles per gallons the automobile can be driven: ";
cin >> miles_Gallon;
cout << endl;
//calculating miles
miles = capacity_Gallons * miles_Gallon;
//display output data
cout << "Number of miles driven wihtout refueling: " << miles << endl;
//pause system for some time for user continuation
system("pause");
} //end main
You should take out that line entirely, and change the later line to double miles = capacity_Gallons * miles_Gallon;.
Instead of your handcrafted rounding code it would be better to use the standard rounding function in the display statement, ... << std::lround(miles) << ... although your assignment stipulation says you should round down , not round to nearest as you are currently doing. (So you can just cast to int there).
You don't need to declare miles there, you can declare it at the point it has a value.
#include<iostream>
int main()
{
//inputting capacity of automobile
double capacity_Gallons;
std::cout << "Enter the capacity of the automobile fuel in gallons: ";
std::cin >> capacity_Gallons;
std::cout << endl;
//inputting the miles per Gallons
double miles_Gallon;
std::cout << "Enter the miles per gallons the automobile can be driven: ";
std::cin >> miles_Gallon;
std::cout << endl;
//calculating miles
double miles = capacity_Gallons * miles_Gallon;
//display output data
std::cout << "Number of miles driven wihtout refueling: " << miles << std::endl;
//pause system for some time for user continuation
system("pause");
}
As an aside, using namespace std is a bad habit.
Related
I'm trying to write a code for annual interest rate that lets you enter any amount, and it will show you approximately how many years it takes for your money to at least double. The given interest rate is 5% yearly. Thing is, it's not working properly and it's displaying absurdly high numbers, like 200 years or so.
#include <iostream>
using namespace std;
int main() {
int deposit;
int counter;
cout << "Deposit an amount NO LESS than 1000." << endl;
cin >> deposit;
for (deposit ;; deposit = 1.05 * deposit) {
counter = counter+1;
if (deposit >= 2 * deposit) {
cout << endl;
cout << "Your money will double in "<< counter <<" years." << endl;
break;
}
}
}
Instead of using a loop, you could calculate the time taken to double the money directly.
The amount of money is not interesting, so you don't need to store the amount of money. It's only the rate of return that's interesting.
You can calculate it directly as log(2) / log(r) where r is the rate of return. For example log(2) / log(1.05) gives you the exact time to double an initial amount of money with a 5% return.
Include the standard <cmath> header to get std::log().
#include <iostream>
#include <cmath>
int main() {
double yearsToDouble = std::log(2) / std::log(1.05);
std::cout << "Your money will double in "<< yearsToDouble << " years." << std::endl;
}
Use a variable to store the initial deposit so that it can be compared to the cumulative amount with interest.
for (float initdeposit = deposit;; deposit = 1.05 * deposit)
{
counter = counter+1;
if (deposit >= 2 * initdeposit)
{
cout << endl;
cout << "Your money will double in "<< counter <<" years." << endl;
break;
}
}
a.exe
Deposit an amount NO LESS than 1000.
1000
Your money will double in 16 years.
Note: No matter what the amount is, the time taken to double will be the same always. :)
if (deposit >= 2 * deposit) {
cout << endl;
cout << "Your money will double in "<< counter <<" years." << endl;
break;
}
In the above if statement you are expecting deposit to be greater than or equal to 2 times of deposit. Which can only be true in case if the value of deposit is zero or less than zero.
I will suggest you to use a temp variable to keep the input value of deposit and proceed.
To add to the other answers, which are largely correct in pointing out that deposit > 2*deposit can never be true (you need a second variable to record the initial value!), the only reason your loop ends at all is because deposit gets so large that 2*deposit "wraps around" due to overflow.
This appears to make 2*deposit bigger than deposit (logically impossible — you need to fix this comparison!) although strictly speaking the results are undefined.
Apparently this happens to you after 200 or so iterations.
As for suggestions to switch to a floating-point type like double, this is tempting, and may be sufficient in this simple case, but as a general rule you should avoid floating-point when you don't need it as it introduces complexities and inaccuracies for very little gain.
I would recommend counting in integer pennies, or tenths of pennies, instead. You can achieve it by multiplying the input by 100 or 1000. The resulting incremental multiplication by 1.05 will have a rounding factor, then, but this is what the banks will be doing too!
This line
if (deposit >= 2 * deposit) {
Will not evaluate to true (unless deposit is negative or barring someedge case). You probably wanted to compare it to an initial value. So after this:
cin >> deposit;
I would put
double initialDeposit = deposit;
And then change the other line to
if (deposit >= 2 * initialDeposit) {
I have coded a program in C++ for an assignment in my C++ Intro class but I have multiple errors in the program but I can't seem to figure out how to get all of the bugs out.
The program is supposed to ask the user for the name of the movie, the number of adult and child tickets sold, and calculate the gross box office profit, net box office profit and the amount paid to the distributor.
I can't seem to figure out how to initialize the variables adultTicketPrice and
childTicketPrice and I thought I declared them and am trying to figure out if they need to get initialized if I already declared them?
And how is the childTicket price out of scope?
And why am I getting the other errors and how can I fix them?
// Michael VanZant
// Flix for Fun Profit Report
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
// Create all double variables
double adultTicketsSold, childTicketsSold, grossBoxProfit, netBoxProfit,
amtPaidDist, adultTicketPrice, childTicketPrice
adultTicketPrice = 12;
childTicketPrice = 7;
cout << fixed << setprecision(2);
// Create the string variable
string movieName;
// Get the name of the movie and store it in the movieName string
cout << "What is the name of the movie?";
getline(cin, movieName);
cout << "\n";
// Cin.ignore to ignore the string variable type
cin.ignore();
// Get the amount of adult and child tickets sold
cout << "How many adult tickets do you want to buy?";
cin >> adultTicketsSold;
cout << "\n";
cout >> "How many child tickets did you want to buy?";
cin >> childTicketsSold;
cout << "\n";
// Calculate the amount of gross box office profit and display it
grossBoxProfit = (childTicketsSold * childTicketPrice) + (adultTicketsSold * adultTicketPrice);
cout << "Gross Box Office Profit: $" << grossBoxProfit;
cout << "\n";
// Calculate the net box profit amount and display it
netBoxProfit = grossBoxProfit * .20;
cout << "Net Box Profit Amount: $" << netBoxProfit;
cout << "\n";
// Calculate the amount paid to distributor and display it
amtPaidDist = grossBoxProfit - netBoxProfit;
cout << "Amount Paid to Distributor is: $" << amtPaidDist;
return 0;
}
When the compiler says "expected initialiser", it has nothing to do with these lines:
adultTicketPrice = 12;
childTicketPrice = 7;
which are actually assignments, not initialisations (though some old C terminology would call the first assignment an initialisation).
No, it's because it thinks you're still on this line, providing declarations and (optionally) initialisers:
double adultTicketsSold, childTicketsSold, grossBoxProfit, netBoxProfit,
amtPaidDist, adultTicketPrice, childTicketPrice
That's because you didn't put a ; at the end of it.
Also:
cout >> "How many child tickets did you want to buy?";
You meant <<.
Fixing those two little typos, the code compiles.
I just starting learning C++. Here is my code:
#include <iostream>
using namespace std;
int main() {
double hours,rate,pay;
// get the number of hours worked
cout << "How many hours did you work?";
cin>> hours;
//Get the hourly pay rate
cout<<"How much did you get paid per hour?";
cin>> pay;
// calculates the pay
pay = hours * rate;
// Display the pay
cout<<"You have earned $" << pay <<endl;
return 0;
}
I have no idea why this program is outputting the wrong numbers:
How many hours did you work?19
How much did you get paid per hour?15
You have earned $4.03179e-313
Maybe I installed the IDE wrong (I am using Eclipse)?:
I think your cin >> pay line is wrong, because you follow it up with pay = hours * rate. Since rate is never assigned to, it just gets junk data in memory, so the output is undefined. Change cin >> pay to cin >> rate
firstly, initializing variables before using them is a good practice so you shoud try this :
double hours = 0, rate = 0, pay = 0;
secondly, you need to replace pay by rate in :
//Get the hourly pay rate
cout << "How much did you get paid per hour?";
cin >> rate;
Amran AbdelKader.
There are two issues with your code.
Your second cin>> call is initializing pay when it should be initializing rate instead:
cin >> rate;
Or, if you are using C++11 or later, you can use std::get_money() instead:
cin >> get_money(rate);
Your cout<< is outputting a double (a floating-point data type) using its default formatting, which may not be suitable for your needs. To display money values, you should be explicit about the formatting, eg:
cout << "You have earned $" << fixed << setprecision(2) << pay << endl;
Or, if you are using C++11 or later, you can use std::put_money() instead:
cout << "You have earned " << put_money(pay) << endl;
Here is the prompt I haven't gotten to all of it yet though:
Implement a class named GasPump that will be used to model a pump at a gas station.
A GasPump object should be able to perform the following tasks:
- Display the amount of gas dispensed
- Display the total amount charged for the amount of gas dispensed
- Set the cost per gallon on gas
- Display the cost per gallon of gas
- Reset the amount of gas dispensed and amount charged before each new usage
- Keep track of the amount of gas dispensed and the total charge
When implementing the GasPump class , you should assume that the gas pump dispenses
.10 gallons of gas per second. Write a test program in main() that prompts the user
to enter the cost per gallon of gas and how many seconds they want to pump gas for.
Then, display the number of gallons of gas pumped, the cost per gallon of gas, and
the total cost of the gas.
I am having problems calculating the amount paid and keep getting logical errors. As this code stands it will compile but it gives garbage for a calculation for amount charged.
#include <iostream>
#include <iomanip>
using namespace std;
class GasPump{
public:
void setCostPerGallon(double cpg){
costPerGallon = cpg;
}
double getCostPerGallon(){
return costPerGallon;
}
void setAmountDispensed(int seconds){
const double dispense = 0.10;
sec = seconds;
amountDispensed = dispense * sec;
}
int getAmountDispensed(){
return amountDispensed;
}
//here is the function I am having problems with, at least I think.
void setAmountCharged(double costPerGallon, double amountDispensed){
amountCharged = costPerGallon * amountDispensed;
}
double getAmountCharged(){
return amountCharged;
}
private:
double costPerGallon;
int sec;
double amountCharged, amountDispensed;
};
int main() {
double cpg = 0.0;
int seconds = 0;
GasPump pump;
cout << "Enter the cost per gallon of gas:";
cin >> cpg;
while(cpg <= 0.0) {
cout << "Enter a value greater than 0:";
cin >> cpg;
}
pump.setCostPerGallon(cpg);
cout << "Enter the amount of seconds you want to pump gas for:";
cin >> seconds;
while(seconds <= 0.0) {
cout << "Enter a value greater than 0:";
cin >> seconds;
}
pump.setAmountDispensed(seconds);
cout << "The gas pump dispensed " << pump.getAmountDispensed() << " gallons of gas." << endl
<< "At $" << pump.getCostPerGallon() << " per gallon, your total is $"
<< fixed << setprecision(2) << pump.getAmountCharged() << "." << endl;
return 0;
You never call pump.setAmountCharged(...), so the member variable amountCharged is whatever the compiler decided to initialize it to when you instantiated pump (typically 0);
To fix this, either get rid of the member variable amountCharged and do the calculation for the amount when getAmountCharged is called, or call setAmountCharged appropriately before calling getAmountCharged.
Here's the first solution:
class GasPump {
...
double getAmountCharged() {
return costPerGallon * amountDispensed;
}
...
};
I'm a beginner programmer, so this is going to look messy, but I keep getting the problem that is mentioned in the title. No matter where I try to put endl; it keeps giving me the same error. Also when I run the code my total for the second store comes out right but the first store total does not. Any idea on how to fix this? I'm using codeblocks on a windows 7 computer.
#include <iostream> //Allows cout/cin
#include <ctime> //Allows time
#include <iomanip> //Allows setprecision
using namespace std;
int main()
{
//Include header
//Input variables
double widgetStores;
double numberSoldFirst1;
double numberSoldFirst2;
double numberSoldSecond1;
double numberSoldSecond2;
double widgetsLeftS1W2;
double widgetsLeftS2W1;
double widgetsLeftS2W2;
//Start Clock
clock_t begin, end;
double time_spent;
begin = clock();
//Prompt for total number in stores
cout << "Total number of widgets at each store starting with :";
cin >> widgetStores;
double widgetStore1=widgetStores;
double widgetStore2=widgetStores;
double widgetsLeftS1W1;
//Prompt for amount sold during first and second week
cout << "How many widgets were sold at Store 1 the first week? ";
cin >> numberSoldFirst1;
cout << "How many widgets were sold at Store 1 the 2nd week? ";
cin >> numberSoldSecond1;
cout << "How many widgets were sold at Store 2 the first week? ";
cin >> numberSoldFirst2;
cout << "How many widgets were sold at Store 2 the 2nd week? ";
cin >> numberSoldSecond2;
//Calculate Number of widgets
widgetsLeftS1W1-=(widgetStore1-numberSoldFirst1);
widgetsLeftS1W2-=(numberSoldFirst1-numberSoldSecond1);
widgetsLeftS2W1-=(widgetStore2-numberSoldFirst2);
widgetsLeftS2W2-=(numberSoldFirst2-numberSoldSecond2);
//Display Values
cout << "Store 1 has " << widgetsLeftS1W2 << " widgets left after the 2nd week.";
cout << "Store 2 has " <<widgetsLeftS2W2 << " widgets left after the 2nd week.";
//Show time elapsed
end = clock();
time_spent = (double)(end - begin) / CLOCKS_PER_SEC;
cout << setprecision(2) << fixed << "****Elapsed time:" <<time_spent/60 << "minutes****";
return 0;
Did you try something like
cout << "Total number of widgets at each store starting with :";
cin >> widgetStores;
cout << endl; //Added this
cin doesn't have a << operator, so you need to send it to cout.
Edit: I found the error you're having. I guess that you are trying to put in lines as literally
endl;
and that doesn't go anywhere...
The only compile error this program has, is that you're using widgetsLeftS1W1, widgetsLeftS1W2, widgetsLeftS2W1 and widgetsLeftS2W2 before initializing them.
You probably need = instead of -=.
When you say
widgetsLeftS1W1 -= (widgetStore1-numberSoldFirst1);
what you actually mean is
widgetsLeftS1W1 = widgetsLeftS1W1 - (widgetStore1-numberSoldFirst1);
The computer doesn't know the value of widgetsLeftS1W1, so it gives you the error.
Conclusion: use
widgetsLeftS1W1 = (widgetStore1 - numberSoldFirst1);
Try initializing the values of
widgetsLeftS1W1
widgetsLeftS1W2
widgetsLeftS2W1
widgetsLeftS2W2
with zero while declaring them at the top.