This program is going to calculate the ratio. The correct output should be 4.50492%, but my output is 0%. I doubt it's the size problem. However, the size of double is 8 bytes, and so type long long is. What's wrong with my program? Thanks.
#include <iostream>
int main()
{
using namespace std;
//cout << "Enter the world's population: ";
long long world = 6898758899;
//cin >> world;
//cout << "Enter the population of US: ";
long long us = 310783781;
//cin >> us;
double ratio = us/world * 100;
char percentage = '%';
cout << "The population of the US is " << ratio << percentage << " of the world population." << endl;
return 0;
}
because "us" and "world" type is long long.So "us/world" is long long.(long)0.0450492 == 0.
the correct spelling is
double ratio = (double)us/(double)world * 100.0;
Related
this is my first time posting on here. Whenever I've gotten stuck on a programming problem, I've typically been able to find enough information to get me unstuck. I'm afraid that the issue I'm having though, I can't quite find an answer to. It's something I'd need someone to look at to tell me what I may be doing wrong in my code.
I have the program running successfully, and it DOES work. The issue however, is that my produced output is off by a few numbers when compared to the expected output on My Programming Lab. I'm really not sure of what to do to produce the correct output. Allow me to post both my source code, and a screenshot MPL's results screen.
SOURCE CODE:
#include <iostream>
using namespace std;
int populationCalculator(int, double, double, int, int);
int main()
{
int startingPopulation, newArrivals, peopleWhoLeft, years,
newPopulation, finalPopulation;
double deathRate, birthRate;
cout << "This program calculates population change.\n";
cout << "Enter the starting population size: ";
cin >> startingPopulation;
while (startingPopulation < 2)
{
cout << "\nThe starting population may not be less than two. Please
re - enter: ";
cin >> startingPopulation;
}
cout << "Enter the annual birth rate (as % of current population): ";
cin >> birthRate;
while (birthRate < 0)
{
cout << "\nBirth rate percent cannot be negative. Please re -
enter:";
cin >> birthRate;
}
birthRate = birthRate / 100;
cout << "Enter the annual death rate (as % of current population): ";
cin >> deathRate;
while (deathRate < 0)
{
cout << "\nDeath rate percent cannot be negative. Please re -
enter: ";
cin >> deathRate;
}
deathRate = deathRate / 100;
cout << "How many individuals move into the area each year? ";
cin >> newArrivals;
while (newArrivals < 0)
{
cout << "\nArrivals cannot be negative. Please re - enter: ";
cin >> newArrivals;
}
cout << "How many individuals leave the area each year? ";
cin >> peopleWhoLeft;
while (peopleWhoLeft < 0)
{
cout << "\nDepartures cannot be negative. Please re - enter: ";
cin >> peopleWhoLeft;
}
cout << "For how many years do you wish to view population changes? ";
cin >> years;
while (years < 1)
{
cout << "\nYears must be one or more. Please re - enter: ";
cin >> years;
}
newPopulation = populationCalculator(startingPopulation, deathRate,
birthRate, newArrivals, peopleWhoLeft);
cout << "\nStarting population: " << startingPopulation << endl;
for (int loopCount = 1; loopCount <= years; loopCount++)
{
newPopulation = populationCalculator(newPopulation, deathRate,
birthRate, newArrivals, peopleWhoLeft);
cout << "Population at the end of year " << loopCount << " is: " <<
newPopulation << endl;
}
system("pause");
return 0;
}
int populationCalculator(int Population, double deathRate, double birthRate,
int newArrivals, int peopleWhoLeft)
{
int newPopulationCount;
newPopulationCount = Population + (Population * birthRate) - (Population
* deathRate) + newArrivals - peopleWhoLeft;
return newPopulationCount;
}
MPL RESULTS:
http://imgur.com/a/mRmpc
I really will appreciate if anyone can help me figure out why my produced output is off by a few numbers.
Step through your code. You're returning an int where you have double and int multiplication. Make sure that you aren't truncating values that might need to be rounded up or down.
Does birth happen before or after death? Should it occur in steps, or all at once like you have shown?
try casting to a double in your operations that involve doubles and integers. For example
birthRate = (double)(birthRate / 100);
deathRate = (double)(deathRate / 100);
Sometimes programming languages will cast a double to an integer, which causes your numbers to be off.
Perhaps the number were rounded off?
I assume this is the case because I noticed you declared some variables in double but the end result is integer. Try to change the data type of the method
populationCalculator(), newPopulation and of course the returning values of the method populationCalculator() from int to double.
I'm new in programming and new in here.
Sorry for stupid question but i have problem with result in my "calculate your age in seconds" code. It gives me weird result like 6.17725e+10 or -6.17414e+10.
Program isn't finished yet but everything except results looks fine (i don't get any error.
Sorry again and I hope for your understanding:)
#include <iostream>
using namespace std;
void title()
{
cout << "Age Calculator" << endl << endl;
}
int byear()
{
cout << "Enter your birth year: ";
int by;
cin >> by;
return by;
}
int bmonth()
{
cout << "Enter your birth month: ";
int bm;
cin >> bm;
return bm;
}
int bday()
{
cout << "Enter your birth day: ";
int bd;
cin >> bd;
return bd;
}
int cyear()
{
int cy;
cout << "Enter current year ";
cin >> cy;
return cy;
}
int cmonth()
{
cout << "Enter current month: ";
int cm;
cin >> cm;
return cm;
}
int cday()
{
cout << "Enter current day: ";
int cd;
cin >> cd;
return cd;
}
void calculate(int by, int bm, int bd, int cy)
{
double y = 31104000;
long double cby = y * by;
long double cbm = 259200 * bm;
long double cbd = 8640 * bd;
long double ccy = 31104000 * cy;
cout << endl << cby << endl;
cout << endl << ccy << endl;
cout << endl << ccy - cby << endl;
}
int main()
{
title();
int by = byear();
int bm = bmonth();
int bd = bday();
int cy = cyear();
int cm = cmonth();
int cd = cday();
calculate(by, bm, bd, cy);
cin.get();
return 0;
}
Like Kenny Ostrom commented, the shown values may look strange due to the scientific notation used by cout. To show all digits, you can change cout's precision using cout.precision(your_precision_here). See question below.
How do I print a double value with full precision using cout?
First, the numeric format you are confused by is "scientific notation". That will be enough info to open up a world of google searches, or you can just force it not to print in scientific notation.
Second, you really want to use a time library for any calendar stuff. It will handle all kinds of calendar weirdness for you, including leap years. Fortunately we have time.h
Third, I recommend using an integer type for seconds, partly to avoid rounding errors and ugly decimals, but mainly because that's what time.h uses. Just make sure it is big enough. My compiler uses a 64 bit integer for time_t, so I used that:
#include <time.h>
#include <memory>
time_t get_age_in_seconds(int year, int month, int day)
{
struct tm birthday;
memset(&birthday, 0, sizeof(birthday));
birthday.tm_year = year - 1900; // years since 1900
birthday.tm_mon = month - 1; // months since January (0,11)
birthday.tm_mday = day; // day of the month (1,31)
time_t birthday_in_seconds = mktime(&birthday);
time_t now = time(NULL);
return now - birthday_in_seconds;
}
Don't use doubles to do the calculation. You're not going to have any fractional values since you're not doing any division.
More importantly, look into mktime(), time(), and difftime(). You should be using these to do your calculation.
I have to create a program to calculate charges for airfare. It's a simple program so far and I am not done adding to it, but every time I run it the result turns out to be 0. Is there something missing in my code? I am a beginner and I would appreciate any advice on improving my code. Thank you.
#include <iostream>
using namespace std;
void main () {
int distance = 0;
int num_bags= 0;
int num_meals= 0;
double distance_price = distance * 0.15;
double bag_price = num_bags * 25.00;
double meal_price = num_meals * 10.00;
double total_airfare = 0.00;
cout << "CorsairAir Fare Calculator" << endl;
cout << "Enter the distance being travelled: " << endl;
cin >> distance;
cout << "Enter number of bags checked: " <<endl;
cin >> num_bags;
cout << "Enter the number of meals ordered: " << endl;
cin >> num_meals;
total_airfare = (distance_price + bag_price + meal_price);
cout << total_airfare;
}
Your confusion is completely understandable - the piece you're missing is that when you assign a variable, you're assigning the left side to the result of the right side at that moment in time. It's not like algebra, where you say f(x) = x + 5 and f(x) is always whatever x + 5 is.
So, you assign double distance_price = distance * 0.15 when distance is 0 (which you just initialized). distance_price remains 0 even after you ask for input and change distance.
Do your price calculations after you ask for input, and everything will work just fine.
You are calculating the distance_price bag_price meal_price with default values i.e. 0 not with the value which you took from user.
Below code works fine and you won't see the issue.
#include <iostream>
using namespace std;
// My compiler did not allow void main so used int main
int main () {
int distance = 0;
int num_bags= 0;
int num_meals= 0;
double distance_price ;
double bag_price ;
double meal_price;
double total_airfare;
cout << "CorsairAir Fare Calculator" << endl;
cout << "Enter the distance being travelled: " << endl;
cin >> distance;
cout << "Enter number of bags checked: " <<endl;
cin >> num_bags;
cout << "Enter the number of meals ordered: " << endl;
cin >> num_meals;
distance_price = distance * 0.15;
bag_price = num_bags * 25.00;
meal_price = num_meals * 10.00;
total_airfare = 0.00;
total_airfare = distance_price + bag_price + meal_price;
cout << total_airfare;
return 0;
}
Result
CorsairAir Fare Calculator
Enter the distance being travelled:
200
Enter number of bags checked:
2
Enter the number of meals ordered:
2
100
I'm working on a currency converter program that converts the old system of British pounds, Shillings, and pence, into their new system, which is a type of Decimal Pound. Where 100 pence equals a pound. Here is the code for the program
#include <iostream>
#include <iomanip>
#include <conio.h>
using namespace std;
int calcNum(int pound, int shilling, int pence)
{
pence = pound*240 + shilling*12 + pence;
return pence;
}
int calcNew(int total_pence, double dec_pound)
{
dec_pound = total_pence / 240;
return dec_pound;
}
int main()
{
int pence;
int shilling;
int pound;
const int OLD_POUND = 240;
const int OLD_SHILLING = 12;
double total_pence;
double dec_pound = 0;
double deci_pound;
cout << "Please Enter the Amount of old pounds: ";
cin >> pound;
cout << endl;
if(cin.fail())
{
cout << "That's not a valid number\n";
cout << "This program will terminate on any keypress!";
_getch();
exit(1);
}
cout << "Please Enter the Amount of old shillings: ";
cin >> shilling;
cout << endl;
if(cin.fail())
{
cout << "That's not a valid number\n";
cout << "This program will terminate on any keypress!";
_getch();
exit(1);
}
cout << "Please Enter the Amount of old pence: ";
cin >> pence;
cout << endl;
if(cin.fail())
{
cout << "That's not a valid number\n";
cout << "This program will terminate on any keypress!";
_getch();
exit(1);
}
total_pence = calcNum(pence, shilling, pound);
deci_pound = calcNew(dec_pound, total_pence);
cout << (5, "\n");
cout << "The total amount in decimal pounds is: ";
cout << setprecision(2) << "\x9c" << deci_pound;
_getch();
return 0;
}
When I run this program however, I'm having a bit of a problem. No matter what the number input is, it always says 0 pounds. Just to make sure that the setprecision function at the end wasn't interfering with the code, I had originally set a cout statement with a _getch() after the two functions to show how much deci_pound came out to be calculated to, and once again, it came out as zero. So my issue seems to be somewhere in the functions running the calculations. If someone could help me with this, I would really appreciate it.
Your calcNew(...) function returns an int, make it return a double. Right now it casts to int which involves stripping the decimals.
In your code, dec_pound is set equal to zero, and you're deci_pound = calcNew(dec_pound, total_pence), which divides 0 by 240 = 0.
The order of the parameters when you call both functions is wrong. Your functions are declared and implemented as:
int calcNum(int pound, int shilling, int pence);
int calcNew(int total_pence, double dec_pound);
And then you call them like this:
total_pence = calcNum(pence, shilling, pound);
deci_pound = calcNew(dec_pound, total_pence);
I am trying to make a program which does a very basic calculation, but for some reason i can't get the code right. It is supposed to calculate the miles per gallon for one trip. You can then add this info multiple times (for different trips) and for each time it should calculate the total miles per gallon (i.e. the average miles per gallon of all the trips). This is the code:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int counter = 1;
double milePerRe, milePerTo = 0, x, y;
cout << "Enter the miles used (-1 to quit): ";
cin >> x;
cout << "Enter gallons: ";
cin >> y;
while (x != -1)
{
milePerRe = x/y;
milePerTo += milePerRe;
milePerTo /= counter;
cout << "MPG this tankful: " << setprecision( 6 ) << fixed << milePerRe;
cout << "\nTotal MPG: " << setprecision( 6 ) << fixed << milePerTo << endl << endl;
counter++;
cout << "Enter the miles used (-1 to quit): ";
cin >> x;
if (x != -1)
{
cout << "Enter gallons: ";
cin >> y;
}
}
system("pause");
return 0;
}
When I run the program and say I enter 10 on the miles and 1 on the number of gallons the first time and the second time, everything works fine. Then if i do it again a third time the calculations begin to become incorrect.
You can not calculate average of averages the way you do it. In your code you are dividing by the counter EACH iteration, while you should divide it only at the end.
Best way to do what you need is something like this:
...
double totalMiles = 0;
double totalGallons = 0;
...
while (x != -1)
{
milePerRe = x/y;
totalMiles += x;
totalGallons += y;
milesPerTo = totalMiles / totalGallons;
...
However, if your task was to explicitly calculate the average of trips (not the average of miles/gallons), you would need to introduce another variable, like this:
...
double currentMilesPerTo;
...
while (x != -1)
{
milePerRe = x/y;
milePerTo += milePerRe;
currentMilesPerTo = milePerTo/counter;
....
cout << "\nTotal MPG: " << currentMilesPerTo;
...
the value of x and y are not being updated properly i guess.after every iteration try to make x and y to zero.
hope it works this way
TNQ