Is something off with my formula for the variables especially for change_in_pennies or is the problem with my choices of the datatypes for the variables? When I input 270 or 280 I get almost everything correct except for the value of pennies where it's a completely random value or number where it should be zero
enter image description here
const double quarter_value {0.25};
const double dime_value {0.1};
const double nickle_value {0.05};
const double penny_value {0.01};
int main() {
int amount{}, change_in_dollars{}, change_in_quarters{},
change_in_dimes{}, change_in_nickles{};
double total{}, change_in_pennies{};
cout << "Enter an amount in cents : ";
cin >> amount;
cout << "You can provide change for this"
" change as follows: " << endl;
total = (static_cast <double> (amount) / 100);
cout << "total: " << total << endl;
change_in_dollars = (amount / 100);
cout << "dollars : " << change_in_dollars << endl;
change_in_quarters = (total - change_in_dollars) / quarter_value;
cout << "quarters : " << change_in_quarters << endl;
change_in_dimes = (total - change_in_dollars - (quarter_value * change_in_quarters)) / dime_value;
cout << "dimes : " << change_in_dimes << endl;
change_in_nickles = (total - change_in_dollars - (quarter_value * change_in_quarters) - (dime_value * change_in_dimes)) / nickle_value;
cout << "nickles : " << change_in_nickles << endl;
change_in_pennies = (total - (change_in_dollars) - (quarter_value * change_in_quarters) - (dime_value * change_in_dimes) - (nickle_value * change_in_nickles)) / penny_value;
cout << "pennies: " << change_in_pennies << endl;
return 0;
}
Like others have commented, the problem is likely that your double-to-int conversions are truncated rather than rounded, making even a tiny round-off error lead to a different result. To avoid this, use purely int arithmetic and work in units of cents. Or if you use doubles, make sure to apply std::round() before casting back to ints.
Related
This question already has answers here:
Why does floating-point arithmetic not give exact results when adding decimal fractions?
(31 answers)
Closed last year.
I'll refer to the below code to explain my question.
typedef long long int ll;
void func(){
ll lli_a = 603828039791327040;
ll lli_b = 121645100408832000;
double d_b = (double)lli_b;
cout << "a " << lli_b - d_b << endl; \\0
cout << "b " << (lli_a - 4*lli_b) - (lli_a - 4*d_b) << endl; \\64
cout << "c " << (lli_a - 4*lli_b) - (lli_a - (ll)4*d_b) << endl; \\64
cout << "d " << (lli_a - 4*lli_b) - (lli_a - 4*(ll)d_b) << endl; \\0
cout << "e " << 4*(ll)d_b - 4*d_b << endl; \\0
cout << "f " << 4*(ll)d_b - (ll)4*d_b << endl; \\0
}
I'm unable to understand why statements b and c have evaluated to 64, while d has evaluated to 0, which happens to be the correct answer.
Both e and f evaluate to 0, so the difference is coming because of subtraction from lli_a I assume. I don't think there is any overflow issue as individual values for each term are coming correctly.
double is a floating point type. Floating point types have limited precision. They cannot represent all numbers - not even all rational numbers. Simply (on your system) 603828039791327040 is a number that cannot be represented by the double datatype. The closest value that is representable happens to be 64 away from the precise value.
You can (likely) get the expected result by using long double which (typically) can represent all values of long long - or you could avoid using floating point in the first place.
Some code to walk you through it, bottom line don't mix doubles with ints implicitly
#include <cassert>
#include <iostream>
#include <type_traits>
// typedef long long int ll; NO , use using and never use aliasing to safe a bit of typing. Aliases are there to introduce meaning not shortcuts
//using namespace std; // also NO
int main()
{
long long int lli_a = 603828039791327040;
long long int lli_b = 121645100408832000;
//double d_b = (double)lli_b; // No this is C++ don't use 'C' style casts
double d_b = static_cast<double>(lli_b);
assert(static_cast<long long int>(d_b) == lli_b); // you are in luck the double can represent your value exectly, NOT guaranteed
std::cout << "a " << lli_b - d_b << "\n"; // endl; \\0 don't use endl unless you have a good reason to flush
long long int lli_b4 = 4 * lli_b;
// use auto to show you this expression evaluates to a double!
auto lli_d_b4 = (lli_a - static_cast<long long int>(4) * d_b); // d_b is double!!! what do you want to do here? Use it as a long long int then cast it first
static_assert(std::is_same_v<double, decltype(lli_d_b4)>);
auto result_c = lli_b4 - lli_d_b4;
// result c is still a double!
static_assert(std::is_same_v<double, decltype(result_c)>);
std::cout << "c " << result_c << "\n";
// long story short don't mix types implicitly and use "C++" style cast explicitly to get the results you want
/*
cout << "b " << (lli_a - 4 * lli_b) - (lli_a - 4 * d_b) << endl; \\64
cout << "c " << (lli_a - 4 * lli_b) - (lli_a - (ll)4 * d_b) << endl; \\64
cout << "d " << (lli_a - 4 * lli_b) - (lli_a - 4 * (ll)d_b) << endl; \\0
cout << "e " << 4 * (ll)d_b - 4 * d_b << endl; \\0
cout << "f " << 4 * (ll)d_b - (ll)4 * d_b << endl; \\0
*/
return 0;
}
I'm writting a C++ program that takes user input and put it inside a file. In this case, it takes in a number (eg. 299.99), but C++ rounds it to 300 (used to be doubles) when using doubles and floats 299.9...
My code:
void Bank::deposit(){
std::cout << "You currently have " << getBalance() << " in your account.\nHow much would you like to deposit? Amount: ";
float amount = optionExists(amount);
if(amount < 1){
std::cout << "Invalid Amount!" << std::endl;
deposit();
}
float moneyInBank = getBalance();
setBalance(moneyInBank + amount);
std::cout << "Your balance of " << moneyInBank << " has been increased to " << getBalance() << std::endl;
std::string theLine = getUsername() + "," + getPassword() + "," + getAccountType() + "," + std::to_string(moneyInBank) + "," + std::to_string(getAdmin());
updateFile(theLine, getUsername(), getPassword(), getAccountType(), getBalance(), (getAdmin()));
displayMenu();
}
When I call the getBalance() method it also returns a float, but as I said, only to one decimal...
Here is a snippet from the text file:
[name,password,type,BALANCE,admin]
lisa,mag24#773,C,24.99,0 ---> What I want (manually entered)
lols,23456,L,30,1 ---> What I got when using doubles
mark,passw0rd,S,24509.9,1 ---> What I got when using floats
Extra Notes: I compile using cmake and code with VSCode
This link may help [link][1]
float iBalance = getBalance();
std::cout<< std::setprecision(2)<<iBalance<< endl;
[1]: https://stackoverflow.com/questions/5907031/printing-the-correct-number-of-decimal-points-with-cout#:~:text=You%20have%20to%20set%20the%20'float%20mode'%20to%20fixed.&text=To%20set%20fixed%202%20digits,ios%3A%3Afixed)%3B%20cout.
Let me preface this by saying I'm still extremely new to C++ and want to keep things as simple as possible. I'm also pretty terrible at math.
Mostly, I'm looking to see if anyone can help my code so it will always give the correct result. I've mostly got it to do what I want, except in one scenario.
My code is trying to find out how many packages of hotdog weiners and how many packages of hotdog buns someone has purchased. Then it tells the user how many hotdogs they can make from that as well as how much leftover weiners or buns they would have. Assuming a package of weiners contains 12 and a package of buns contains 8, this is what I have come up with so far:
#include <iostream>
#include <cmath>
using namespace std;
void hotdog(int a, int b){ //a = weiner packages, b = bun packages
int weiners = 12 * a;
int buns = 8 * b;
int total = (weiners + buns) - (weiners - buns);
int leftOverWeiners = total % weiners;
int leftOverBuns = total % buns;
int totalHotDogs = total / 2;
cout << "You can make " << totalHotDogs << " hotdogs!" << endl;
if (leftOverWeiners > 0){
cout << "You have " << leftOverWeiners << " weiners left over though." << endl;
}else if (leftOverBuns > 0){
cout << "You have " << leftOverBuns << " buns left over though." << endl;
}
}
int main(){
int a;
int b;
cout << "Let's see how many hotdogs you can make!" << endl;
cout << "How many weiner packages did you purchase?: ";
cin >> a;
cout << "How many bun packages did you purchase?: ";
cin >> b;
hotdog(a, b);
return 0;
}
With this, I can always get the correct answer if the ratio of buns to weiners is the same or if there are more weiners than buns.
Because of the way I've set up total and/or leftOverBuns (lines 9, 11), I will never get the correct answer to how many left over buns there will be. I know there must be a simpler way to do this if not a way to modify my current code but I am stumped.
I know I left virtually zero notation, so if you would like some please let me know!
You're making it too complicated. Try this:
if(weiners > buns)
{
cout << "You can make " << buns << " hotdogs!" << endl;
cout << "with " << weiners-buns << " weiners left over" << endl;
return;
}
cout << "You can make " << weiners << " hotdogs!" << endl;
if(buns > weiners)
{
cout << "with " << buns-weiners << " buns left over" << endl;
}
The smaller of {buns, weiners} is the number of hot dogs, and the if-then blocks determine whether the function will report leftover buns or weiners.
#include <iostream>
void hotdog( int weinerspackages, int bunspackages ){
const int weinersPerPackage = 12;
const int bunsPerPackage = 8;
const int totalweiners = weinerspackages * weinersPerPackage;
const int totalbuns = bunspackages * bunsPerPackage;
int leftoverweiners = 0;
int leftoverbuns = 0;
int amountOfHotdogs = 0;
if( totalweiners > totalbuns ){
leftoverweiners = totalweiners - totalbuns;
amountOfHotdogs = totalbuns;
leftoverbuns = 0;
}
else if( totalbuns > totalweiners ){
leftoverbuns = totalbuns - totalweiners;
amountOfHotdogs = totalweiners;
leftoverweiners = 0;
}
else{
amountOfHotdogs = totalweiners;
leftoverweiners = 0;
leftoverbuns = 0;
}
std::cout << "You can make: " << amountOfHotdogs << " Hotdogs" << std::endl;
std::cout << "Leftover Weiners: " << leftoverweiners << " || Leftover Buns: " << leftoverbuns << std::endl;
}
int main(){
int PackagesW = 8;
int PackagesB = 12;
hotdog( PackagesW, PackagesB );
system("pause");
return 0;
}
Note: It is possible to do this with less variables, I declared this amount of variables to make it easier to understand what the numbers represent.
Assuming that it only takes one of each to make a hotdog, you can find which of the ingredients you have the least, and the amount of hotdogs you can make will be limited by the amount of that ingredient, that is why amountOfHotdogs takes the value of the lesser one. If both are equal in amount, then amountOfHotdogs can take the amount of either.
Only the ingredient with the larger amount will have leftovers, therefore leftoverweiners = totalweiners - totalbuns; when totalweiners > totalbuns and vice-versa.
I have tried tirelessly to get this right, but nothing seems to work. A lot of what I do brings me to an error 'Control may reach end of non-void function'.
Basically, we created a program to output gas usage statistics. What I am stuck on is:
"Gas will rise in price from the defined initial value to the defined final value over the course of 4 years, then remain fixed at that higher value for the next 4 years."
I feel like there should be a loop or function for this, but every time I make NUM_YEARS an int rather than a const, no matter what the program tells me 'Control may reach end of non-void function.'
Below is the program:
#include <cstdlib>
#include <iostream>
using namespace std;
const int MILES_PER_YEAR = 21000;
const double CITY_PERCENT = 45.0;
const double HIGHWAY_PERCENT = 55.0;
const double CITY_MPG = 51.0;
const double HIGHWAY_MPG = 45.0;
const double USABLE_GAS = 9.0;
const double INITIAL_PRICE = 3.359;
const double FINAL_PRICE = 6.00;
const int NUM_YEARS = 8; //This will be the total number of years
double gasPrice(int day);
int main(int argc, char * argv[]) {
cout << "Driving the Toyota Prius" << endl;
double daily_miles = MILES_PER_YEAR / 365.0;
double daily_city_miles = daily_miles * CITY_PERCENT/100.0;
double daily_highway_miles = daily_miles*HIGHWAY_PERCENT/100.0;
double daily_gas_consumed = daily_highway_miles / HIGHWAY_MPG +
daily_city_miles / CITY_MPG;
double gas_in_tank = USABLE_GAS;
double price;
double amount_purchased;
double gallons_purchased;
double total_gas_purchases = 0;
for(int day = 0;day < 365*8; day++) { //If the day is less than the total number of days in 8 years, add one day
cout << "Driving summary for day " << day << endl;
cout << " highway miles: " << daily_highway_miles << endl;
cout << " city miles : " << daily_city_miles << endl;
cout << " gas consumed : " << daily_gas_consumed << endl;
gas_in_tank = gas_in_tank - daily_gas_consumed;
cout << " gas in tank : " << gas_in_tank << endl;
if (gas_in_tank < 0.0) {
cout << " BUY GAS" << endl;
gallons_purchased = USABLE_GAS - gas_in_tank;
price = gasPrice(day);
cout << " price today is : " << price << endl;
cout << " Gallons purchased: " << gallons_purchased << endl;
cout << " fillup cost : " << gallons_purchased * price << endl;
total_gas_purchases = total_gas_purchases + gallons_purchased * price;
cout << " total gas cost : " << total_gas_purchases << endl;
gas_in_tank = USABLE_GAS;
}
}
system("PAUSE");
return EXIT_SUCCESS;
}
double gasPrice(int day, int YEAR_NUM) {
if (int day=365) { //call YEAR_NUM, for day=365, increase YEAR_NUM by 1
YEAR_NUM++;
day = 0;
}
if (YEAR_NUM >= 4) {
double currentPrice = FINAL_PRICE;
currentPrice;
}
if (YEAR_NUM < 4) { //conditional price for the first four years
double dailyIncrease = (FINAL_PRICE - INITIAL_PRICE) / (NUM_YEARS * 365);
double currentPrice = (INITIAL_PRICE + day * dailyIncrease);
return currentPrice;
}
}
You need to return something in gasPrice that is outside of the for loop. The compiler is saying there is a chance that neither of the while conditions will be met, in which case there is no value to return.
On another note, the while loops do not make a lot of sense the way they are written. Just make them if statements.
I think if you move "return currentPrice;" out of those two while loops, it will fix the problem.
Function gasPrice has no return statement outside the for loop. As the function has a return type that is not void then if the return statement is absent the behaviour of the function will be undefined.
I've been having a slight issue with my program, what I'm trying to do is develop a way for users to simulate the possible strengths of passwords. This is assuming that all passwords are permutations (weird I know, but I presume that this is to stop data from becoming even more unwieldy.) using the equation...
//n!/(n-r)! when n! = (e^-n)*(n^n) sqrt(2(pi)n). When n is number of characters in use and r is length of password
No matter what I put I receive nan as an answer. I thought that perhaps my equation was off (maybe somehow I was dividing by zero) so I reworked it and simplified it a great deal. But that didn't seem to be the problem, though I feel that this got me closer to being correct. But I had the thought that maybe numeric overflow is having an effect here? But I really don't know how to fix something like that. I tried jumping from different data types but nothing seemed to work.
I have a problem with the modulus too. It returns back numbers less than zero for time, so with my noobish knowledge that tells me that maybe I'm overflowing it again but how else am I going to use % without defining it as an int? Maybe fixing the above problem will work out this one?
I would be beyond grateful for any help given to me. How does one go about dealing with return values of nan? Is there a step by step status quo for solving it? Is it pretty much always overflow or could it be something else?
The code itself.
#include <iostream>
#include <cmath>
using namespace std;
const int SECONDS_IN_YEAR = 31556926;
const int SECONDS_IN_DAY = 86400;
const int SECONDS_IN_HOUR = 3600;
const int SECONDS_IN_MIN = 60;
int main()
{
int passwordLength ,characterSymbols;
double instructionsPerSecond, instructionSuccess;
////////////////////////////////////////////////////////////////////////////////
//Equations needed
// n!/(n-r)!
//n is the number of letters in the alphabet
//and r is the number of letters in the password
// n! = (e^-n)*(n^n) sqrt(2(pi)n)
double numeratorFactorial = (pow(M_E,-characterSymbols))
*(pow(characterSymbols,characterSymbols))
*(sqrt(2*M_PI*characterSymbols));
// (n-r)
double characterMinusLength= (characterSymbols-passwordLength);
// (n-r)! = (e^-(n-r)) * ((n-r)^(n-r)) * sqrt(2(pi)(n-r))
double denominatorFactorial = ((pow(M_E, -(characterMinusLength)))*
(pow((characterMinusLength),(characterMinusLength)))
* (sqrt(2*M_PI*(characterMinusLength))));
// n!/(n-r)!
long double passwordPermutation = (numeratorFactorial / denominatorFactorial);
// (passwords)* (instructions/Password) * (seconds/instruction) = sec
int passwordSeconds = (passwordPermutation * instructionSuccess)
*(1/instructionsPerSecond);
int passwordMin = passwordSeconds / SECONDS_IN_MIN ;
int passwordHour = passwordSeconds / SECONDS_IN_HOUR;
int passwordDay = passwordSeconds / SECONDS_IN_DAY ;
int passwordYear = passwordSeconds / SECONDS_IN_YEAR;
////////////////////////////////////////////////////////////////////////////////
//Explain purpose of program
cout << "This program is designed to simulate the strength of passwords." << endl;
//Ask for alphabet
cout << "But first, share with me the max number of characters you'd be using."
<< endl;
cin >> characterSymbols;
//Reflect information
cout << "We will be using " << characterSymbols << " character symbols to "
<< " construct the password.\n" << endl;
///////////////////////////////////////////////////////////////////////////////
//Input length of password
cout << "\n\nWill you give me the length of proposed password?" << endl;
cin >> passwordLength;
//Repeat information
cout << "The password length will be " << passwordLength << "." <<endl;
//cout permutations
cout << "This would lead to " << passwordPermutation << " unique password\n"
<< endl;
////////////////////////////////////////////////////////////////////////////////
//Ask for computer strength
cout << "How powerful is this computer? How many instructions per second " << endl;
cout << "can it accomplish?" << endl;
cin >> instructionsPerSecond;
//Read out computer strength
cout << "The computer can do " << instructionsPerSecond << " instructions/second"
<< endl << endl;
////////////////////////////////////////////////////////////////////////////////
//Ask for instructions/password
cout << "The number of instructions needed to test your password is." << endl
<< endl;
cin >> instructionSuccess;
//reflect
cout << "This computer can do " << instructionSuccess
<< " instructions/password" << endl;
////////////////////////////////////////////////////////////////////////////////
cout << "\n\nThe amount of seconds it'll take to crack this passcode is... "
<< endl << passwordSeconds << " seconds.\n\n\n\n\n" << endl;
////////////////////////////////////////////////////////////////////////////////
//Reflect all information in an easily readable table
cout << "Number of character symbols using... " << characterSymbols << endl;
cout << "Length of password... " << passwordLength << endl;
cout << "Number of permutations... " << passwordPermutation << endl;
cout << "Instructions per second... " << instructionsPerSecond << endl;
cout << "Instructions per password..." << instructionSuccess << endl;
cout << endl << endl << endl;
////////////////////////////////////////////////////////////////////////////////
//Add in conversions for min, hour, day, years
cout << "Number of seconds to break..." << passwordSeconds << endl;
cout << "Converted to minutes..." << passwordMin << endl;
passwordMin = passwordSeconds / SECONDS_IN_MIN;
passwordSeconds = passwordSeconds % SECONDS_IN_MIN;
cout << "Converted to hours..." << passwordHour << endl;
passwordHour = passwordSeconds / SECONDS_IN_HOUR;
passwordSeconds = passwordSeconds % SECONDS_IN_MIN;
cout << "Converted to days..." << passwordDay << endl;
passwordDay = passwordSeconds / SECONDS_IN_DAY;
passwordSeconds = passwordSeconds % SECONDS_IN_DAY;
cout << "Converted to years..." << passwordYear << endl;
passwordYear = passwordSeconds / SECONDS_IN_YEAR;
passwordSeconds = passwordSeconds % SECONDS_IN_YEAR;
return (0);
}
"nan" stands for "not a number". This is happening because you have declared the variables characterSymbols and passwordLength without giving them an initial value.
You must initialize any variable before you use it - if you don't then you will have undetermined behavior. For example:
int x;
int y;
int z = x + y;
There is no way to predict what z will be equal to here because we don't know what x or y are equal to. In the same way, your code should be something like:
int characterSymbols = 10; //or whatever you want the initial value to be
...
double numeratorFactorial = (pow(M_E,-characterSymbols))
*(pow(characterSymbols,characterSymbols))
*(sqrt(2*M_PI*characterSymbols));
In this way, numeratorFactorial will have a valid value.
It appears you think you are declaring "equations" when you are actually declaring variables. You write:
double numeratorFactorial = (pow(M_E,-characterSymbols))
*(pow(characterSymbols,characterSymbols))
*(sqrt(2*M_PI*characterSymbols));
But characterSymbols isn't defined, only "declared". characterSymbols is declared above it, but it doesn't have a value... yet. Later on you use cin to get a value into it, but when you first declare numeratorFactorial you can't simply expect the program to insert the value into numeratorFactorial when characterSymbols changes.
Some definitions are probably in order: The statement double numeratorFactorial = some_value; creates a variable named numeratorFactorial and uses some_value to fill that variable immediately. What you want is a function, a logical statement that you can "pass values" to so values are generated when you need them. For example, for your numerator factorial:
double numeratorFactorial(double characterSymbols) {
return (pow(M_E,-characterSymbols))
*(pow(characterSymbols,characterSymbols))
*(sqrt(2*M_PI*characterSymbols));
}
int main() {
std::cout << "Numerator Factorial test: " << numeratorFactorial(5.0) << std::endl;
}
Note that you cannot declare a function within the main function.
This sort of thing is programming fundamentals, and it seems like you are trying to run before you've learned to walk. Get a good book like C++ Primer and pace yourself.