Convert money input into coins - c#

ive just started some classes on c# and have been given an assignment with the following rules:
Prompt the user to enter an amount of dollars and cents. For example 1.18
- Display the number of quarters, dimes, nickels, and pennies to make that amount
Example If they entered 2.16 it should say:
8 quarters, 1 dimes, 1 nickels, 1 pennies
the problem that i run into is that this only seems to work if they type the money value as a whole. so if they wanted to type $1.18 they would type 118 and it would work just fine, but as soon as they type 1.18 it crashes. another example would be if they were to type 765 for $7.65 it would work fine, however if they type it correctly as 7.65 it would fail. sorry for the lame question, im super new, thanks for the help!
int totalCash;
Console.WriteLine("input money");
string moneyString = Console.ReadLine();
totalCash = int.Parse(moneyString);
int quarter = totalCash / 25;
totalCash %= 25;
int dime = totalCash / 10;
totalCash %= 10;
int nickel = totalCash / 5;
totalCash %= 5;
int penny = totalCash / 1;
totalCash %= 1;
Console.WriteLine("{0} quarters, {1} dimes, {2} nickels, {3} pennies", quarter, dime, nickel, penny);
```

There are lots of ways get the result but this the best approach I ever tried :
public static string ConvertMoneyIntoCoins(double money)
{
int cents = (int)(Math.Round(money, 2) * 100);
var coins = new[] {
new { Name = "Quarters", Value = 25 }, new { Name = "Dimes", Value = 10 },
new { Name = "Nickels", Value = 5 }, new { Name = "Pennies", Value = 1 }
};
var changes = coins.Select(coin => new { Amt = Math.DivRem(cents, coin.Value, out cents), Coin = coin }).Where(x => x.Amt != 0).ToList();
var strBld = new StringBuilder();
foreach (var change in changes)
{
strBld.Append(change.Amt + " " + change.Coin.Name + ", ");
}
return strBld.ToString();
}

It's working when you enter whole number should be the clue you pay attention to. If you assume the whole number is dollars, you can not mod by a whole number. All of your divisors are a factor of 100 too big. When you do that, you'll notice that you have the wrong data type as well. Note that i disagree with using tryparse when debugging as it eats errors. You should be running it in debug mode and then you would get an actual stack trace and a line it crashes at.

Related

Sum range using loop, calculate sum of odd and even numbers

Hi I am sick of searching I could not find the exact code for my question.
I need to code the sum of the odd numbers from 1 to 100
and sum of the even numbers from 2 to 100.
This is what i have so far.
Thank you so much
// 1) using for statement to Sum Up a Range of values using Interactive
Console.WriteLine(" Sum Up a Range of values entered by User ");
Console.WriteLine();
// 2) Declare the Variables to be used in the Project
string strFromNumber, strToNumber;
int fromNumber, toNumber;
int sum = 0;
int i, even = 0, odd = 0;
int[] array = new int[10];
// 3) Prompt the User to Enter the From Number to Sum From
Console.Write("Enter the From Number to Sum From: ");
strFromNumber = Console.ReadLine();
fromNumber = Convert.ToInt32(strFromNumber);
// 4) Prompt the User to Enter the To Number to Sum To
Console.Write("Enter the To Number to Sum To: ");
strToNumber = Console.ReadLine();
toNumber = Convert.ToInt32(strToNumber);
// 5) Use for statement to Sum up the Range of Numbers
for (i = fromNumber; i <= toNumber; ++i)
{
sum += i;
}
if //(array[i] % 2 == 0) //here if condition to check number
{ // is divided by 2 or not
even = even + array[i]; //here sum of even numbers will be stored in even
}
else
{
odd = odd + array[i]; //here sum of odd numbers will be stored in odd.
}
Console.WriteLine("The Sum of Values from {0} till {1} = {2}",
fromNumber, toNumber, sum);
Console.ReadLine();
There is no need to write the complex code which you have written.
Problem is to calculate the sum of arithmetic progression. The formula to find the sum of an arithmetic progression is Sn = n/2[2a + (n − 1) × d] where, a = first term of arithmetic progression, n = number of terms in the arithmetic progression and d = common difference.
So in case of odd numbers its a = 1, n = 50 and d = 2
and in case of even numbers its a = 2, n = 50 and d = 2
and if you try to normalize these above formulas, it will be more easy based on your problem.
the sum of the first n odd numbers is Sn= n^2
the sum of the first n even numbers is n(n+1).
and obviously, it's very simple to loop from ( 1 to 99 with an increment of 2 ) and ( 2 to 100 with an increment of 2 )
In the simplest case, you can try looping in fromNumber .. toNumber range while adding
number either to even or to odd sum:
// long : since sum of int's can be large (beyond int.MaxValue) let's use long
long evenSum = 0;
long oddSum = 0;
for (int number = fromNumber; number <= toNumber; ++number) {
if (number % 2 == 0)
evenSum += number;
else
oddSum += number;
}
Console.WriteLine($"The Sum of Values from {fromNumber} till {toNumber}");
Console.WriteLine($"is {evenSum + oddSum}: {evenSum} (even) + {oddSum} (odd).");
Note, that you can compute both sums in one go with a help of arithmetics progression:
private static (long even, long odd) ComputeSums(long from, long to) {
if (to < from)
return (0, 0); // Or throw ArgumentOutOfRangeException
long total = (to + from) * (to - from + 1) / 2;
from = from / 2 * 2 + 1;
to = (to + 1) / 2 * 2 - 1;
long odd = (to + from) / 2 * ((to - from) / 2 + 1);
return (total - odd, odd);
}
Then
(long evenSum, long oddSum) = ComputeSums(fromNumber, toNumber);
Console.WriteLine($"The Sum of Values from {fromNumber} till {toNumber}");
Console.WriteLine($"is {evenSum + oddSum}: {evenSum} (even) + {oddSum} (odd).");
From the code snippet you shared, it seems like the user gives the range on which the sum is calculated. Adding to #vivek-nuna's answer,
Let's say the sum of the first N odd numbers is given by, f(n) = n^2 and
the sum of the first N even numbers is given by, g(n) = n(n + 1).
So the sum of odd numbers from (l, r) = f(r) - f(l - 1).
Similarly, the sum of even numbers from (l, r) = g(r) - g(l - 1).
Hope this helps.

How do I display each number with corresponding value?

I have an assignment where I need to calculate the amount of money for 2 people where we have 2 different interest rates. I need to display the amount of money that they would have at each of the given age. The issue is that it only prints the final amount which is 60 years old, how do I print the correct amount at the correct age? Here is the code
Console.WriteLine("*************************Investing vs.Savings ************************* \n");
Console.WriteLine("{0,-25} {1,-30} {2,-30}","Age", "Linda's Account", "John's Account");
Console.Write("-----------------------------------------------------------------------\n");
for(int age=20;age<=60;age+=10)
{
double Linda = 1000;
double John = 1000;
for (int year=1;year<=40;year++)
{
double retLin = 0.06;
double retJon = 0.015;
Linda += Linda * retLin;
John += John * retJon;
}
Console.WriteLine("{0,-25}{1,-30:0.00} {2,-35:0.00}", age, Linda, John);
}
Console.Read();
If I figured it right, your desired response is a line of output for each person's balance on each deacde. To do this you only need one iteration in wich balances are increased based on each person's interest rate.
But to calculate the interest rate correctly, it should be added to the balance on every year. So a fixed inner loop of 10 iterations is needed for each decade.
The code is:
double Linda = 1000;
double John = 1000;
double retLin = 0.06;
double retJon = 0.015;
for (int age = 30; age <= 60; age += 10)
{
for (int i = 0; i < 10; i++)
{
Linda += Linda * retLin;
John += John * retJon;
}
Console.WriteLine("{0,-25}{1,-30:0.00} {2,-35:0.00}", age, Linda, John);
}
Note that this will not print tha balance on the starting decade (you can simply print the starting values before the loop operations).
I think this is what you need (comments in code):
Console.WriteLine("*************************Investing vs.Savings ************************* \n");
Console.WriteLine("{0,-25} {1,-30} {2,-30}", "Age", "Linda's Account", "John's Account");
Console.Write("-----------------------------------------------------------------------\n");
// It always is good idea to store info in variables, to give
// them meaning and easily parametrize the code.
var baseAge = 20;
var ageStep = 10;
var finalAge = 60;
// Of course, it would not make sense if you'd have just simple loop
// i = 0, i < limit, i++.
for (int age = baseAge; age <= finalAge; age += ageStep)
{
double Linda = 1000;
double John = 1000;
// Here you missed starting point, as it always calculated
// as if we were in first loop - we need account for that.
for (int year = age; year <= 40; year++)
{
double retLin = 0.06;
double retJon = 0.015;
Linda += Linda * retLin;
John += John * retJon;
}
Console.WriteLine("{0,-25}{1,-30:0.00} {2,-35:0.00}", age, Linda, John);
}
Console.Read();

Pennies on Pay - Math Calculation - C#

I'm trying to double the amount of pennies for X amount of days.
So, 3 days = 4 pennies, 4 days = 8 pennies, etc
I'm stuck on getting the right code put in: (I know I'm close and I know I'm missing something silly. I've spent 5 hours on this. I just want to see the solution so my mind will put it together on how it works...)
I finally got it... now... how can I clean this up?? I'm still learning to write in less code... but I'm following the Starting Out w/ Visual C# book for now...
// Local variables. /
int daysWorkedInputValue;
decimal currentPayRate, newPayRate, totalPaySalary;
int daysWorked;
int count = 0;
currentPayRate = 0.01m;
totalPaySalary = 0m;
daysWorkedInputValue = int.Parse(daysWorkedInputTextBox.Text);
if (int.TryParse(daysWorkedInputTextBox.Text, out daysWorked))
{
if (daysWorked >= 0)
{
// Continue to process the input. /
if (daysWorkedInputValue == 0)
{
totalPayCalcLabel.Text = "$0.00";
}
if (daysWorkedInputValue == 1)
{
totalPayCalcLabel.Text = "$0.01";
}
// The following loop calculates the total pay. /
while (count <= (daysWorked - 1))
{
// Calculate the total pay amount. /
if (count == 1)
{
currentPayRate = 0.01m;
totalPayCalcLabel.Text = currentPayRate.ToString("c");
}
currentPayRate = currentPayRate * 2;
totalPaySalary = currentPayRate;
if (count >= 1)
{
totalPayCalcLabel.Text = totalPaySalary.ToString("c");
}
// Add one to the loop counter. /
count = count + 1;
// Return focus back to the organisms TextBox. /
daysWorkedInputTextBox.Focus();
}
I see a pretty obvious pattern here:
3 days -> 2^(3-1) = 4 pennies
4 days -> 2^(4-1) = 8 pennies
So you want to solve for the equation:
pennies = 2^(days-1)
I haven't run your code to see what's wrong (nothing's changing the value of count or daysWorked so I'm assuming you'll end up stuck in an infinite loop), but this should work just fine:
var pennies = Math.Pow(2, days - 1);

Get values from an array

This code get a user to enter 5 numbers, stores the in an array, and works out the average
double average;
double variance;
int i;
int[] arr = new int[5]; // 5 size array
for (i = 0; i < 5; i++)
{
Console.Write("\n Enter your number:\t");
arr[i] = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("\n");
average = arr.Sum() / 5.0;
Console.WriteLine("\n The average is {0}", average);
Console.ReadLine();
I am trying to work out the variance which is (number – average) * (number – average).
However I am unsure on how to pull out each number from the array and perform this calculation?
Any help much appreciated thanks
You can get the standard deviation as follows:
double average = arr.Average();
double sumOfSquaresOfDifferences = arr.Select(val => (val - average) * (val - average)).Sum();
double sd = Math.Sqrt(sumOfSquaresOfDifferences / arr.Length);
Your Question
Make an Extension Method.. not Tested but it should work if what is described here is correct
static class MathsExtensions
{
public static double GetVariance(this double[] values)
{
var avg = values.Average();
return values.Select(value => (value - avg) * (value - avg)).Sum() / values.Count();
}
}
Just gave it a little test.
double[] arr = { 8, 7, 9, 10, 6 };
Console.WriteLine(arr.GetVariance());
Console.ReadLine();
It returns 2 which - according to my link - is correct.
This might be helpful in the feauture
If you next Time have a similar Problem, you should propably just google like "how do i calculate variance" and then create your algorithm based on the theory. But alaways look up if there does already exist a solution

Calculating the note mix to dispense

I need to figure out a cash mix algorithm to dispense notes from the ATM. The goals of the algorithm are:
To calculate the note mix to dispense the required amount to the customer.
While doing so, to attempt the emptying of the cash cassettes as evenly as possible, so ideally (but not mandatory), the cash will run out in all cassettes at the same time.
The user wants to get different amounts of cash, such as 500$, 1200$, 6000$, etc.
There is no average. The algorithm needs to figure out which notes and how many of them to dispense. Of course, the cassettes in the ATM can change to different values / counts.
Another limitation is that the ATM can present only 30 notes at the time, so the algorithm has to divide the notes in bunches, if calculated number of notes exceeds this limit, while considering the goal above (equal emptying).
Here is what i came up with:
//Represents a typical cash cassette.
class Cassette
{
public int Denom { get; set; } //Denomination: (USD)50, (USD)100, etc.
public int Count { get; set; } //Number of notes.
}
//Our cassettes.
List<Cassette> OriginalCashCassettes = new List<Cassette>();
List<Cassette> CloneCashCassettes = new List<Cassette>();
//Populated.
OriginalCashCassettes.Add(new Cassette { Denom = 50, Count = 1000 });
OriginalCashCassettes.Add(new Cassette { Denom = 100, Count = 1000 });
OriginalCashCassettes.Add(new Cassette { Denom = 200, Count = 1000 });
//Pass original cassettes to clone cassettes.
CloneCashCassettes = OriginalCashCassettes;
//Calculate mix for requested amount.
CalculateNoteMix(6000);
And the calculation itself:
private void CalculateNoteMix(int reqAmount)
{
//1. Check if the amount is higher than combined counts.
int totalCounts = 0;
foreach (var item in CloneCashCassettes)
{
totalCounts += item.Denom * item.Count;
}
if (totalCounts < reqAmount)
{
Console.WriteLine("You're trying too high - maximum amount available is: " + totalCounts);
return;
}
//2. Check if the amount is dispensable with current denoms.
int lowestDenom = CloneCashCassettes.Min(c => c.Denom);
if (reqAmount % lowestDenom != 0)
{
Console.WriteLine("Unable to dispense amount with current denoms");
return;
}
//3. Calculate note mix to dispense.
List<Cassette> noteMix = new List<Cassette>();
do
{
//Sort cash cassettes by highest count first.
CloneCashCassettes = CloneCashCassettes.OrderByDescending(c => c.Count).ToList();
//Check if highest count denom can cover the amount.
if (CloneCashCassettes[0].Denom <= reqAmount)
{
//Check if this denom already exists in the mix.
Cassette noteMixCassette = noteMix.Find(n => n.Denom == CloneCashCassettes[0].Denom);
if (noteMixCassette == null)
{
//Add denom to the note mix.
noteMix.Add(new Cassette { Denom = CloneCashCassettes[0].Denom, Count = 1 });
}
else
{
//Increase denom count in the note mix.
noteMixCassette.Count += 1;
}
//Reduce denom count in the cash cassette.
CloneCashCassettes[0].Count -= 1;
//Reduce the amount by denom.
reqAmount -= CloneCashCassettes[0].Denom;
}
else
{
//The amount is smaller than denom => the denom is unusable - remove it.
CloneCashCassettes.RemoveAt(0);
}
//Keep looping until the amount is 0.
} while (reqAmount > 0);
//Print resulting note mix.
Console.WriteLine("For the amount of " + reqAmount + ", our note mix is:");
foreach (var item in noteMix)
{
Console.WriteLine("Denom: " + item.Denom + " x " + "Count: " + item.Count + " = " + item.Denom * item.Count);
}
}
Using this code, if the user asks for $400, then the note mix is:
Denom: 50 x Count: 2 = 100
Denom: 100 x Count: 1 = 100
Denom: 200 x Count: 1 = 200
Or if the user asks for $25,000, then:
Denom: 50 x Count: 72 = 3600
Denom: 100 x Count: 72 = 7200
Denom: 200 x Count: 71 = 14200
Problems:
This code appears to work fine with denoms of 50 and higher. However, it has a problem with the denom of 20. Any idea how to resolve it?
Example:
OriginalCashCassettes.Add(new Cassette { Denom = 20, Count = 1000 });
OriginalCashCassettes.Add(new Cassette { Denom = 50, Count = 1000 });
OriginalCashCassettes.Add(new Cassette { Denom = 100, Count = 1000 });
The user asks for $200, which is dispensable.
I start to subtract: 200-100-50-20 = 30 - 20 = 10 -> unable to dispense.
Same problem with denom of 20 exists in the check if the amount is dispensable (#2 in code).
Example: The cassettes configured as above with denom of 20. User asks for $210, which should be dispensable (100+50+20+20+20).
Any ideas how to improve this algorithm in general, so it will be more efficient / faster?
Thanks.
The problem you've encountered, basically, is that you're algorithm leads you to a place where you cannot dispense any more... a dead end (ie, left with $10 to dispense but you do not have that denomination).
What I would do to combat this is to generate all possible permutations of valid dispensations, and then pick which one is "best" or most optimal in terms of rules such as "even dispensation of bills". There may be some shortcuts you can take later on, such as ruling out obviously bad choices, but you'll understand the "optimization" bit much easier if the thing actually works!
I started off with this example (http://www.dotnetperls.com/change) which is a rather rudimentary algorithm for determining the permutations of change available for a given set of coins and a required amount. This is the same basic problem as yours.
public static void Main(string[] args)
{
List<int> notes = new List<int>();
List<int> amounts = new List<int>() { 50,100,200 };
Change(notes, amounts, 0, 0, 250);
}
static void Change(List<int> notes, List<int> amounts, int highest, int sum, int goal)
{
//
// See if we are done.
//
if (sum == goal)
{
Display(notes, amounts);
return;
}
//
// See if we have too much.
//
if (sum > goal)
{
return;
}
//
// Loop through amounts.
//
foreach (int value in amounts)
{
//
// Only add higher or equal amounts.
//
if (value >= highest)
{
List<int> copy = new List<int>(notes);
copy.Add(value);
Change(copy, amounts, value, sum + value, goal);
}
}
}
Here is a live example: http://rextester.com/HIJEQC83701
Asking this code for the permutations for $250 using combinations of 50's,100's and 200's gives the following output:
50: 5
100: 0
200: 0
50: 3
100: 1
200: 0
50: 1
100: 2
200: 0
50: 1
100: 0
200: 1
From there, its easy enough to pick the option that either
a) Uses the most even spread of notes
b) Uses a spread of notes which leaves the overall casettes in the most balanced position.
I'll leave that bit to you!

Categories