Given a type Money that is a structured type with two int fields, dollars and cents. Assume that an array named monthlySales with 12 elements, each of type Money has been declared and initialized.
Assume that a Money-variable yearlySales has also been declared. Write the necessary code that traverses the monthlySales-array and adds it all up and stores the resulting total in yearlySales. Be sure make sure that yearlySales ends up with a valid value, i.e. a value of cents that is less than 100.
Now i'm not asking for the answer but, i'm asking how do i approach it. simply because i'm not sure how to address the question like how to code it. I have understand the first paragraph of the question respectively. here is my snippet of code. now im just stuck on how to compute it. i just need a bit of guidance. Thanks!
the code i have so far, accesses the array I have of 12 elements and assigns them random numbers of dollars and cents respectively.
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <cmath>
using namespace std;
struct Money
{
int dollars,cents;
};
int main()
{
Money monthlySales[12], yearlySales;
for (int i = 0; i < 12; i++)
{
monthlySales[i].cents =rand()%99;
monthlySales[i].dollars =rand();
}
return 0;
}
Write the necessary code that traverses the monthlySalesarray and
adds it all up and stores the resulting total in yearlySales. Be sure
make sure that yearlySales ends up with a valid value , i.e. a value
of cents that is less than 100.
Money monthlySales[12], yearlySales;
yearlySales.cents = 0;
yearlySales.dollars = 0;
for (int i = 0; i < 12; i++)
{
yearlySales.cents += monthlySales[i].cents; // Add up the cents
yearlySales.dollars += monthlySales[i].dollars; // Add up the dollars
yearlySales.dollars += yearlySales.cents / 100; // If cents > 100, increase dollars appropriately.
yearlySales.cents = yearlySales.cents % 100; // If cents > 100, set it to the remainder.
}
//to compute Sum
for (int i = 0; i < 12; i++)
{
yearlySales.cents +=monthlySales[i].cents;//keeps adding yearlySales cents for each month
yearlySales.dollars +=monthlySales[i].dollars;//keeps adding yearlySales dollars
}
//if cents 100 convert it into dollars eg:720cents is convereted to 7$ 20 cents and 7 dollars is added to yearly dollars
if(yearlySales.cents > =100)
{
yearlySales.dollars+=yearlySales.cents/100;
yearlySales.cents=yearlySales.cents%100;
}
This works too!
float dollar = 0;
float cent = 0;
for (int i = 0; i < 12; i++) {
dollar += monthlySales[i].dollars;
cent += monthlySales[i].cents;
do {
if (cent > 100 ) {
dollar += 1;
cent -= 100;
}
}while (cent > 100);
}
yearlySales.dollars = dollar;
yearlySales.cents = cent;
Related
The question is to find the number of interesting numbers lying between two numbers. By the interesting number, they mean that the product of its digits is divisible by the sum of its digits.
For example: 459 => product = 4 * 5 * 9 = 180, and sum = 4 + 5 + 9 = 18; 180 % 18 == 0, hence it is an interesting number.
My solution for this problem is having run time error and time complexity of O(n2).
#include<iostream>
using namespace std;
int main(){
int x,y,p=1,s=0,count=0,r;
cout<<"enter two numbers"<<endl;
cin>>x>>y;
for(int i=x;i<=y;i++)
{
r=0;
while(i>1)
{
r=i%10;
s+=r;
p*=r;
i/=10;
}
if(p%s==0)
{
count++;
}
}
cout<<"count of interesting numbers are"<<count<<endl;
return 0;
}
If s is zero then if(p%s==0) will produce a divide by zero error.
Inside your for loop you modify the value of i to 0 or 1, this will mean the for loop never completes and will continuously check 1 and 2.
You also don't reinitialise p and s for each iteration of the for loop so will produce the wrong answer anyway. In general limit the scope of variables to where they are actually needed as this helps to avoid this type of bug.
Something like this should fix these problems:
#include <iostream>
int main()
{
std::cout << "enter two numbers\n";
int begin;
int end;
std::cin >> begin >> end;
int count = 0;
for (int number = begin; number <= end; number++) {
int sum = 0;
int product = 1;
int value = number;
while (value != 0) {
int digit = value % 10;
sum += digit;
product *= digit;
value /= 10;
}
if (sum != 0 && product % sum == 0) {
count++;
}
}
std::cout << "count of interesting numbers are " << count << "\n";
return 0;
}
I'd guess the contest is trying to get you to do something more efficient than this, for example after calculating the sum and product for 1234 to find the sum for 1235 you just need to add one and for the product you can divide by 4 then multiply by 5.
Write a program that calculates how much a person would earn over a period of time if his or her salary is one penny the first day and two pennies the second day, and continues to double each day. The program should ask the user for the number of days.
The output earnings should be displayed in a dollar amount, not the number of pennies.
Input Validation: Do not accept a number less than 1 for the number of days worked.
Basically, the output displays the correct answer mathematically it just does not add them together. I am not sure on what to do to fix that issue.
//Declare Variables
int numDays = 1;
double money = 0.01;
double totalPay;
//Initialize or input i.e. set variable values
cin>>numDays;
//Map inputs -> outputs
while (numDays < 1)
{
cout<<"Enter a positive value ONLY!\n";
cin>>numDays;
}
for (int i = 1; i <= numDays; i++)
{
cout<<"Pay = $"<<money;
money *=2;
}
//Exit stage right or left!
return 0;
Expected Output
Pay·=·$0.03
My Output
Pay·=·$0.01Pay·=·$0.02
//System Libraries
#include <iostream>//Input/Output Library
#include <iomanip>
using namespace std;
//User Libraries
//Global Constants, no Global Variables are allowed
//Math/Physics/Conversions/Higher Dimensions - i.e. PI, e, etc...
//Function Prototypes
//Execution Begins Here!
int main(int argc, char** argv) {
//Set the random number seed
//Declare Variables
int numDays = 1;
double totalPay;
double dayPay;
double money = 1;
//Initialize or input i.e. set variable values
cin>>numDays;
//Map inputs -> outputs
while (numDays < 1)
{
cout<<"Enter a positive value ONLY!\n";
cin>>numDays;
}
for(int i = 1; i <= numDays; i++)
{
dayPay = money / 100;
totalPay += dayPay;
money *=2;
}
cout<<"Pay = $"<<fixed<<setprecision(2)<<totalPay;
//Exit stage right or left!
return 0;
}
I'm working on a fibonacci algorithm for really big numbers (100k th number). I need to make this run faster though, but just a couple of seconds and I ran out of ideas. Is there any way to make it faster? Thanks for help.
#include <iostream>
using namespace std;
int main() {
string elem_major = "1";
string elem_minor = "0";
short elem_maj_int;
short elem_min_int;
short sum;
int length = 1;
int ten = 0;
int n;
cin >> n;
for (int i = 1; i < n; i++)
{
for (int j = 0; j < length; j++)
{
elem_maj_int = short(elem_major[j] - 48);
elem_min_int = short(elem_minor[j] - 48);
sum = elem_maj_int + elem_min_int + ten;
ten = 0;
if (sum > 9)
{
sum -= 10;
ten = 1;
if (elem_major[j + 1] == NULL)
{
elem_major += "0";
elem_minor += "0";
length++;
}
}
elem_major[j] = char(sum + 48);
elem_minor[j] = char(elem_maj_int + 48);
}
}
for (int i = length-1; i >= 0; i--)
{
cout << elem_major[i];
}
return 0;
}
No matter how good optimizations you perform on a given code, without changing the underlying algorithm you can only optimize it marginally. Your approach is with linear complexity and for big values it will quickly become slow. A faster implementation of Fibonacci numbers is by doing matrix exponentiation by squaring on the matrix:
0 1
1 1
This approach will be with logarithmic complexity which is asymptotically better. Perform a few exponentiations of this matrix and you'll notice that the n + 1st Fibonacci number is at its lower right corner.
I suggest you use something like cpp-bigint (http://sourceforge.net/projects/cpp-bigint/) for your big numbers.
The code would look like this then
#include <iostream>
#include "bigint.h"
using namespace std;
int main() {
BigInt::Rossi num1(0);
BigInt::Rossi num2(1);
BigInt::Rossi num_next(1);
int n = 100000;
for (int i = 0; i < n - 1; ++i)
{
num_next = num1 + num2;
num1 = std::move(num2);
num2 = std::move(num_next);
}
cout << num_next.toStrDec() << endl;
return 0;
}
Quick benchmark on my machine:
time ./yourFib
real 0m8.310s
user 0m8.301s
sys 0m0.005s
time ./cppBigIntFib
real 0m2.004s
user 0m1.993s
sys 0m0.006s
I would save some precomputed points (especially since you are looking for really big numbers)
ie say I saved 500th and 501st fib number. Then if some one asks me what is 600th fib? I would start computing from 502 rather than from 1. This would really save time.
Now the question how many points you would save and how would select the points to save?
The answer to this question totally depends on the application and probable distribution.
Here's the problem.
A group of students are members of a club that travels annually to different locations. Their destinations in the past have included Indianapolis, Phoenix, Nashville, Philadelphia, San Jose, and Atlanta. This spring they are planning a trip to Eindhoven.
The group agrees in advance to share expenses equally, but it is not practical to share every expense as it occurs. Thus individuals in the group pay for particular things, such as meals, hotels, taxi rides, and plane tickets. After the trip, each student's expenses are tallied and money is exchanged so that the net cost to each is the same, to within one cent. In the past, this money exchange has been tedious and time consuming. Your job is to compute, from a list of expenses, the minimum amount of money that must change hands in order to equalize (within one cent) all the students' costs.
Input
Standard input will contain the information for several trips. Each trip consists of a line containing a positive integer n denoting the number of students on the trip. This is followed by n lines of input, each containing the amount spent by a student in dollars and cents. There are no more than 1000 students and no student spent more than $10,000.00. A single line containing 0 follows the information for the last trip.
Output
For each trip, output a line stating the total amount of money, in dollars and cents, that must be exchanged to equalize the students' costs.
Sample Input
3
10.00
20.00
30.00
4
15.00
15.01
3.00
3.01
0
Sample Output
$10.00
$11.99
My code works for some test cases, but fails at others. I think it's because of a precision error in the float. However, I can't find the error.
For example,
Input:
4
9999.1
9999.1
9999.0
9999.1
Output:
$0.06
However, the output should be $0.07
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#define MAX 1000
using namespace std;
float money[MAX];
int main(){
int numOfStudents;
int i; // loop counter
double average; // of the costs
double negDiff, posDiff; // |amount-average|
double minDiff;
float total; // all the costs added together
while(scanf("%d", &numOfStudents) == 1){
if(numOfStudents == 0){
break;
}
memset(money, 0, sizeof(money));
total = 0;
for(i = 0; i < numOfStudents; i++){ // scan for the cost of each student - input into array
double m;
scanf("%lf", &m);
money[i] = m;
total += m;
}
average = total/numOfStudents;
negDiff = 0;
posDiff = 0;
for(i = 0; i < numOfStudents; i++){ // find the difference between average and each cost -> add together
if(money[i] > average){
posDiff += (long) ((money[i] - average) * 100.0) / 100.0;
}
else{
negDiff += (long) ((average - money[i]) * 100.0) / 100.0;
}
}
minDiff = 0;
if(posDiff > negDiff){ // find the minimum value for all to equal
minDiff = negDiff;
}
else{
minDiff = posDiff;
}
printf("$%.2lf\n", minDiff);
}
return 0;
}
If you are chopping the positive and negative differences upto 2 decimal places, chop the average also. This gives the result you are expecting (simplified working code)
#include <stdio.h>
int main() {
int n, i;
double average, negDiff, posDiff, minDiff, total;
while (scanf("%d", &n) == 1 && n != 0) {
double money[n];
total = 0.0;
for (i = 0; i < n; i++) {
scanf("%lf", &money[i]);
total += money[i];
}
average = (long) ((total / n) * 100.0) / 100.0;
negDiff = posDiff = 0.0;
for (i = 0; i < n; i++) {
if (money[i] > average)
posDiff += (long) ((money[i] - average) * 100.0) / 100.0;
else
negDiff += (long) ((average - money[i]) * 100.0) / 100.0;
}
minDiff = posDiff > negDiff ? negDiff : posDiff;
printf("$%.2lf\n", minDiff);
}
return 0;
}
Input
3
10.00 20.00 30.00
4
15.00 15.01 3.00 3.01
4
9999.1 9999.1 9999.0 9999.1
0
Output
$10.00
$11.99
$0.07
See http://ideone.com/cxhvlL
Well... you might be right. You really shouldn't be reading the money in as floats.
scanf ("%d.%d", &dollars, &pennies);
int m = dollars * 100 + pennies;
As for solving the problem in general, just make sure you stick to integral division
int average = total / numStudents;
int leftover = total % numStudents;
// numStudents - leftover students need to have paid $average
// leftover students need to have paid $average + 1
int paid = 0;
int recieved = 0;
for (int i = 0; i < numStudents; ++i)
{
// Since we start with the lowest amount owed, money array needs to have been
// sorted such that the student who paid the least comes first.
owed_money = average;
if (i > numStudents - leftover)
owed_money += 1;
if (money[i] < owed_money)
paid += owed_money - money[i];
else if (money[i] > owed_money)
recieved += money[i] - owed_money;
}
assert (paid == recieved);
Maybe there's a better way to do it? In any case, it's a hard problem, but I can promise your solution shouldn't contain any floating point arithmetic.
Calculate the average only down to cents rest needs to be dropped. That means we will be putting x cents in the side pot and since x is going to be less than n, in the end even if you distribute it only few will get and they will be atmost one cent more than others. So they are all with in the cents.
Now with that said. Here is the simple code for that
int main( )
{
int n;
cin >> n;
while( n ) {
vector<double> v;
while( n-- ) {
double x;
cin >> x;
v.push_back( x );
}
double avg = accumulate( begin(v), end(v), 0.0 ) / v.size();
avg = ((int)(avg*100))/100.00;
double exchange = 0;
for ( auto x : v ) { if ( x < avg ){ exchange += avg - x; } }
cout << exchange << endl;
cin >> n;
}
return 0;
}
and for this input
3
10.00
20.00
30.00
4
15.00
15.01
3.00
3.01
4
9999.1
9999.1
9999.0
9999.1
0
output is
10
11.99
0.07
I am trying to count the amount of dollar and coin denominations in a grand total by using a series of while loops. When I get down to the coins however, I am off by a penny. When I enter say 99.95, I get the output 3 quarters, 1 dime, 1 nickel, and 4 pennies. I've narrowed the problem down to a floating point accuracy issue. However all the solutions I've researched haven't been applicable in my situation. Any pointers?
#include <iostream>
using namespace std;
int main()
{
float amount;
cout<<"enter amount" << endl;
cin>>amount;
int pennies=0, nickels=0, dimes=0, quarters=0, ones=0, fives=0,
tens=0,
twenties=0, fifties=0, hundreds=0;
while (amount >= 100)
{
hundreds = hundreds +1;
amount = amount - 100;
}
while (amount >= 50)
{
fifties = fifties +1;
amount = amount - 50;
}
while (amount >= 20)
{
twenties = twenties +1;
amount = amount - 20;
}
while (amount >= 10)
{
tens = tens +1;
amount = amount - 10;
}
while (amount >= 5)
{
fives = fives +1;
amount = amount - 5;
}
while (amount >= 1)
{
ones = ones +1;
amount = amount - 1;
}
while (amount >= .25)
{
quarters = quarters +1;
amount = amount - .25;
}
while (amount >= .10)
{
dimes = dimes +1;
amount = amount - .10;
}
while (amount >= .05)
{
nickels = nickels +1;
amount = amount - .05;
}
while (amount >= .01)
{
pennies = pennies +1;
amount = amount - .01;
}
cout<<endl<<"pennies:"<< pennies;
cout<<endl<<"nickels:"<<nickels;
cout<<endl<<"dimes:"<<dimes;
cout<<endl<<"quarters:"<<quarters;
cout<<endl<<"ones:"<<ones;
cout<<endl<<"fives:"<<fives;
cout<<endl<<"tens:"<<tens;
cout<<endl<<"twenties:"<<twenties;
cout<<endl<<"fifties:"<<fifties;
cout<<endl<<"hundreds:"<<hundreds<<endl;
return 0;
}
Don't use floating point in cases where you need exact values. 99.95 can't be exactly represented in a float or double, a bit like 1/3 can't be exactly represented using a finite number of normal decimal digits.
As Doug T. suggested, you can use an integer to hold the number of pennies. When the user types 123.45, read it as two integers, and then store it as 12345 pennies, not as 123.45 dollars.
In this case, you can also try to change your last while (amount >= .01) to something like while (amount >= .005). It's not a solution that can be generally recommended, and if this is a real-life bank application you really should avoid it, but it will help against at least some of the errors.
You should be using fixed-point values in this case, not floating-point.
Although people think of money in terms of dollars, which aren't exact, money is measured in cents, which are exact. Just count the number of cents, divide by 100 to get the dollar amount, and take the modulus to get the cent amount. Floating-point is not the proper tool in this case.
Binary floating point numbers cannot, in general, represent fractional decimal values, even if the total number of decimals is small. For example, 0.1 cannot be represented exactly.
To deal with exact values different approaches exist which all amount to using a different base than 2. Depending on tge specific needs the approaches are more or less involved. The easieast approach for your case is to use a fixed precision instead of a variable precision. To compute with fixed precision you'd just use an integer which represents the value you actually want multiplied by a suitable power of 10. Depending on the amount of computations you do you can either package the logic into a class or distribute it throughout the code. In a "real" application I'd package it into a class, in an assignment (homework, interview, etc.) I'd probably just apply the logic directly to an int.
Here's the fixed code, I used TJD's advice and instead of using .01 i used .0099 instead. For my problem that seems to work, thanks guys!
#include <iostream>
using namespace std;
int main()
{
float amount;
cout<<"enter amount" << endl;
cin>>amount;
int pennies=0, nickels=0, dimes=0, quarters=0, ones=0, fives=0,
tens=0,
twenties=0, fifties=0, hundreds=0;
float p = .0099, n = .0499, d = .099, q = .2499;
while (amount >= 100)
{
hundreds = hundreds +1;
amount = amount - 100;
}
while (amount >= 50)
{
fifties = fifties +1;
amount = amount - 50;
}
while (amount >= 20)
{
twenties = twenties +1;
amount = amount - 20;
}
while (amount >= 10)
{
tens = tens +1;
amount = amount - 10;
}
while (amount >= 5)
{
fives = fives +1;
amount = amount - 5;
}
while (amount >= 1)
{
ones = ones +1;
amount = amount - 1;
}
while (amount >= q)
{
quarters = quarters +1;
amount = amount - q;
}
while (amount >= d)
{
dimes = dimes +1;
amount = amount - d;
}
while (amount >= n)
{
nickels = nickels +1;
amount = amount - n;
}
while (amount >= p)
{
pennies = pennies +1;
amount = amount - p;
}
cout<<endl<<"pennies:"<< pennies;
cout<<endl<<"nickels:"<<nickels;
cout<<endl<<"dimes:"<<dimes;
cout<<endl<<"quarters:"<<quarters;
cout<<endl<<"ones:"<<ones;
cout<<endl<<"fives:"<<fives;
cout<<endl<<"tens:"<<tens;
cout<<endl<<"twenties:"<<twenties;
cout<<endl<<"fifties:"<<fifties;
cout<<endl<<"hundreds:"<<hundreds<<endl;
return 0;
}