Program about getting breakdown in c# - c#

I am reviewing for my test tomorrow.. and I've encountered a problem in my program (I need to create a program that will display the breakdown of the entered amount.. and I am having a problem with the cents...)
Console.Write("Enter amount: ");
double amt = double.Parse(Console.ReadLine());
thou = (int)amt / 1000;
change = (int)amt % 1000;
fivehun = (int)change / 500;
change = change % 500;
twohun = (int)change / 200;
change = change % 200;
hun = (int)change / 100;
change = change % 100;
fifty = (int)change / 50;
change = change % 50;
twenty = change / 20;
change = change % 20;
ten = (int)change / 10;
change = change % 10;
five = (int)change / 5;
change = change % 5;
one = (int)change / 1;
change = change % 1;
twencents = (int)(change / .25);
change = change % .25; //there was an error here.. starting here
tencents = (int)(change / .10);
change = change % .10;
fivecents = (int)(change / .05);
change = change % .05;
onecent = (int)(change / .01);
change = change % .01;
Console.WriteLine("The breakdown is as follows: ");
Console.WriteLine("Php 1000 ={0} ", thou);
Console.WriteLine("Php 500 ={0} ", fivehun);
Console.WriteLine("Php 200 ={0} ", twohun);
Console.WriteLine("Php 100 ={0} ", hun);
Console.WriteLine("Php 50 ={0} ", fifty);
Console.WriteLine("Php 20 ={0} ", twenty);
Console.WriteLine("Php 10 ={0} ", ten);
Console.WriteLine("Php 05 ={0} ", five);
Console.WriteLine("Php 01 ={0} ", one);
Console.WriteLine("Php 0.25 ={0} ", twencents);
Console.WriteLine("Php 0.10 ={0} ", tencents);
Console.WriteLine("Php 0.05 ={0} ", fivecents);
Console.WriteLine("Php 0.01 ={0} ", onecent);
Console.ReadKey();
The error said that I cannot convert double to int so I tried to convert it my casting it
change = (double) change % .25;
still an error..

Use double change = 0; instead of int change = 0;

EDITED
initially make double change = 0 and and split the input amt to 2 variables
double wholeValues = (int)amt;
double decimalValues = amt - wholeValues;
then change
thou = (int)amt / 1000;
change = (int)amt % 1000;
make it as
thou = (int)wholeValues / 1000;
change = (int)wholeValues % 1000;
Otherwise you will be removing the decimal values at this point
but you are missing a cast to int at
twenty = (int) change / 20;
modules by 1 will give the same value again, start cent calculation with the new variable decimalValues
one = (int)change / 1;
change = decimalValues * 100;
twencents = (int)(change / 25);
change = change % 25;
tencents = (int)(change / 10);
change = change % 10;
fivecents = (int)(change / 5);
change = change % 5;
if we use modules with decimal values you might sometime end up with incorrect values
for example for .30 cents, it will represent .25 cents = 1, .05 cents = 0,
.01 cents= 4

finally got it!
int thou, fivehun, twohun, hun, fifty, twenty, ten, five, one;
double change = 0; // added this one as suggested
Console.Write("Enter amount: ");
double amt = double.Parse(Console.ReadLine());
thou = (int)amt / 1000;
change = amt % 1000; //remove the int (change should be double)
fivehun = (int)change / 500;
change = change % 500;
twohun = (int)change / 200;
change = change % 200;
hun = (int)change / 100;
change = change % 100;
fifty = (int)change / 50;
change = change % 50;
twenty = (int) change / 20; //added int here
change = change % 20;
ten = (int)change / 10;
change = change % 10;
five = (int)change / 5;
change = change % 5;
one = (int)change / 1;
change = change % 1;
int twencents = (int)(change / 0.25);
change = change % 0.25;
int tencents = (int)(change / 0.10);
change = change % 0.10;
int fivecents = (int)(change / 0.05);
change = change % 0.05;
int onecent = (int)(change / 0.01);
change = change % 0.01;

Related

For loop not printing what I expect. Need assistance

int marsHeight = ml.getHeight() / 100 * 100; // measure by 100s despite height value
int chartHeight = (marsHeight >= 1000) ? marsHeight : 1000;
for (int i = 0; i <= (chartHeight / 100); i++)
{
if (i == 0)
{
Console.WriteLine("{0}m: \t*", (marsHeight - (i * 100))); // in order to print in descending order: (height - (i * 100)
continue;
}
Console.WriteLine("{0}m:", (marsHeight - (i * 100)));
}
I want my program to print out this if marsHeight is greater than 1000 (and it currently does):
[marsHeight]m:
[marsHeight - 100]m:
...
1000m:
900m:
800m:
...
0m: // this works perfectly!
Currently if marsHeight is less than 1000 (like 990)the program prints out:
900m: *
800m:
...
0m:
-100m:
What I want is this if it's less than 1000m:
1000m:
900m: *
800m:
...
0m:
I'm new to programming. Where am I going wrong with my logic?
Change this
int chartHeight = (marsHeight >= 1000) ? marsHeight : 1000;
to
int chartHeight = (marsHeight <= 1000) ? marsHeight : 1000;
^
and if you want the output of to be same in both the condition like if it greater or smaller. You can make it like Not Equal to Like
int chartHeight = (marsHeight =! 1000) ? marsHeight : 1000;
^^
// First get the value.
int height = ml.getHeight();
// Now round to nearest even value.
int chartHeight = height / 100 * 100;
// Find initial value of cycle.
int forStart;
if (chartHeight > 1000)
forStart = chartHeight;
else
forStart = chartHeight < 0 ? 0 : 1000;
// Also you can simplify cycle.
for (int i = forStart; i >= 0; i -= 100)
if(i==chartHeight)
Console.WriteLine("{0}m:*", i);
else
Console.WriteLine("{0}m:", i);
The output will be:
if height 990
1000m
900m*
...
0m
if height >1000
1100m*
1000m
...
0m
if height 540
1000m
...
500m*
...
0m

How to Improve runtime for Iterative Function

My codes runtime is getting quite long, it has to iterate maybe 30,000 times and that takes around 30 sec on my computer but longer on the clients. I'm wondering if I can get any tips to speed up the calculations. The iterative functions has to put the value as close to zero as possible and it decreases or increases until the conditions are met. I sped it up by increasing by $1 then when it gets closer to the range it increments by $0.1 for precision.
I Broke it into nodes. There's an initial node, then it checks difference of left node then difference of right node. Which ever produces a smaller difference it goes in that direction until difference is as small as possible.
//Current Node
double InitialFinalPayment = bruteforceFlexibleAmortization(0);
double intialPaymentAmount = Calc_Payment(Findper() - FindSkipNMonths(), Findnint(),
Findpv() + InterestPaid, Findfv(), Findcf(), Findpf(), Finddisc(),
Findbep()), 2);
double diffInitial = Math.Abs(intialPaymentAmount - InitialFinalPayment);
decimal runningIncrement = 1M;
double nextPayment = 0;
//Node Ahead
Double incrementOutcome = bruteforceFlexibleAmortization(runningIncrement);
Double incrementPayment = intialPaymentAmount + (double)runningIncrement;
Double diffincrement = Math.Abs(incrementPayment - incrementOutcome);
//Node Behind
Double decrementOutcome = bruteforceFlexibleAmortization(-runningIncrement);
Double decrementPayment = intialPaymentAmount - (double)runningIncrement;
Double diffdecrement = Math.Abs(decrementPayment - decrementOutcome);
if (diffincrement < diffInitial)
{
runningIncrement += 1.0M;
double nextValue = bruteforceFlexibleAmortization(runningIncrement);
nextPayment = intialPaymentAmount + (double)runningIncrement;
double diffNext = Math.Abs(nextPayment - nextValue);
while (diffNext < diffdecrement)
{
diffdecrement = diffNext;
runningIncrement += 1.0M;
nextValue = bruteforceFlexibleAmortization(runningIncrement);
nextPayment = intialPaymentAmount + (double)runningIncrement;
diffNext = Math.Abs(nextPayment - nextValue);
}
diffincrement = diffNext;
runningIncrement -= 0.01M;
nextValue = bruteforceFlexibleAmortization(runningIncrement);
nextPayment = intialPaymentAmount + (double)runningIncrement;
diffNext = Math.Abs(nextPayment - nextValue);
while (diffNext < diffincrement)
{
diffincrement = diffNext;
runningIncrement -= 0.01M;
nextValue = bruteforceFlexibleAmortization(runningIncrement);
nextPayment = intialPaymentAmount + (double)runningIncrement;
diffNext = Math.Abs(nextPayment - nextValue);
}
return nextPayment + (double)0.01M;
}
else if (diffdecrement < diffInitial)
{
runningIncrement += 1.0M;
double nextValue = bruteforceFlexibleAmortization(-runningIncrement);
nextPayment = intialPaymentAmount - (double)runningIncrement;
double diffNext = Math.Abs(nextPayment - nextValue);
while (diffNext < diffdecrement)
{
diffdecrement = diffNext;
runningIncrement += 1.0M;
nextValue = bruteforceFlexibleAmortization(-runningIncrement);
nextPayment = intialPaymentAmount - (double)runningIncrement;
diffNext = Math.Abs(nextPayment - nextValue);
}
diffincrement = diffNext;
runningIncrement -= 0.01M;
nextValue = bruteforceFlexibleAmortization(-runningIncrement);
nextPayment = intialPaymentAmount - (double)runningIncrement;
diffNext = Math.Abs(nextPayment - nextValue);
while (diffNext < diffincrement)
{
diffincrement = diffNext;
runningIncrement -= 0.01M;
nextValue = bruteforceFlexibleAmortization(-runningIncrement);
nextPayment = intialPaymentAmount - (double)runningIncrement;
diffNext = Math.Abs(nextPayment - nextValue);
}
return nextPayment - (double)0.01M;
}
return InitialFinalPayment;
}
The only idea I have is by increasing/decreasing running increment to be a larger value and making that value smaller as it gets closer to the value. Like how it's 1 then 0.1, maybe 10 then 1 then 0.1 but it's definitely not gonna be clean code
If your bruteforceFlexibleAmortization is monotonic you should try using similar approach that's used by binary search instead of changing your input by the same value all the time.
var currentValue = 50;
var lastLower = 0;
var lastGreater = 100;
do
{
var currentResult = calculateResult(initialValue);
if(currentResult < expectedResult)
{
lastLower = currentValue;
currentValue = (currentValue + lastGreater) / 2;
}
else
{
lastGreater = currentValue;
currentValue = (currentValue + lastLower) / 2;
}
} while (Math.Abs(currentResult - expectedResult) < epsilon)
It will be a little different for you, because you need to call 2 methods, but you should get the point.
e.g. If you're trying to interpolate square root for a given n to a certain precision using your approach would be really slow. With binary-like you can get much more iterations to get close interpolation.

Is there a possible loop for this?

I just started to learn C# and only know really basic stuff. So this question may be easy to you, but very hard to me. The more detail in your answer, the better.
The next line of code will check if a studentnumber is real or fake. The number is real when the sum of all the characters (when multiplied by their place number) are a multiple of 11.
Console.WriteLine("What is your studentnumber?");
stnum = Console.ReadLine();
var stnumint = Convert.ToInt32(stnum);
var ans1 = (stnumint % 10 - stnumint % 1) / 1;
var ans2 = (stnumint % 100 - stnumint % 10) / 10;
var ans3 = (stnumint % 1000 - stnumint % 100) / 100;
var ans4 = (stnumint % 10000 - stnumint % 1000) / 1000;
var ans5 = (stnumint % 100000 - stnumint % 10000) / 10000;
var ans6 = (stnumint % 1000000 - stnumint % 100000) / 100000;
var ans7 = (stnumint % 10000000 - stnumint % 1000000) / 1000000;
var control = ans1 * 1 + ans2 * 2 + ans3 * 3 + ans4 * 4 + ans5 * 5 + ans6 * 6 + ans7 * 7;
var endnum = control % 11;
if (endnum == 0)
{
Console.WriteLine("You have got a valid studentnumber.");
}
else
{
Console.WriteLine("Check if your studentnumber is correct. If it is, you are not a student.");
}
Take for example studentnumber 9232753. When calculating: (9*7 + 2*6 + 3*5 + 2*4 + 7*3 + 5*2 + 3*1) % 11, the answer will be 0.
How can I write this line of code into a smaller loop?
One equivalent loop would be:
int control = 0;
int power10 = 1; // var to save an expensive `Math.Power` call
for (int i = 1; i <= 7; i++)
{
control += ((stnumint % (power10*10) - stnumint % power10) / power10) * i;
power10 *= 10;
}
I would highly recommend not using var for built-in types like int, string, etc. You leave the resulting type at the mercy of the compiler which can give you unexpected results. Save var for when the actual type is difficult (or impossible) to determine at design-time.
var totalAns = 0;
for (int i = 1; i <= 10000000; i *= 10)
{
ans += (stnumint % (10*i) - stnumint % i) / i;
}
Here is the part for calculation. If you need to save stnumint, copy it another variable.
int stnumint=...; //must be sure, that data type is n
int checksum=0;
int i=1;
while(stnumint>0)
{
checksum=(stnumint%10)*i;
i++;
//in real numbers will look like floor(stnumint/10)
//will automaticly floor because of data type int
stnumint=stnumint/10;
}

C# program for printing out copies

My program is taking 2 dollars for each printed copy for the first 100 papers that is copied out. If the user prints out more than a hundread copies, for each copy that is above hundread it takes 1dollar per copy (So if I want to print out 101 copies, the price should be 200 + 1, 1 dollar for the 101:th copy and 2 dollars each for the first 100 copies). Here is my Code:
int CopyCost = 2;
int ammountOfCopies;
int discount = 1;
Console.WriteLine("How many copies would you like?: ");
ammountOfCopies = int.Parse(Console.ReadLine());
for (int i = 0; i < ammountOfCopies; i++)
{
if (ammountOfCopies > 100)
CopyCost = 2 - discount;
else
CopyCost = 2;
CopyCost *= ammountOfCopies;
}
Console.WriteLine("The total cost for your copies is: {0} ", CopyCost);
Console.ReadLine();
But the problem I have is, if I choose to write out 101 copies, it discounts every copy to 1 dollar, and not only the one above 100.
This is more a math problem than a coding one. You need to take the amount of copies at or below 100 and multiply it with the normal price. Then take the amount of copies over 100 and multiply with the discounted price. No need for the for loop.
Break the problem into small pieces in the code, for instance, like so:
int price = 2;
int discountedPrice = price - 1;
int amountAtNormalPrice = Math.Min(amountOfCopies, 100);
int amountAtDiscountPrice = Math.Max(amountOfCopies - 100, 0);
int amountTotal = (amountAtNormalPrice * price) + (amountAtDiscountedPrice * discountedPrice);
You are looping over each of your copies (numberOfCopies, btw, not amountOfCopies) and applying the calculation each time. You should calculate directly instead; there's no need for a loop in this situation:
if (numberOfCopies > 100)
{
CopyCost = 200 + (numberOfCopies - 100);
}
else
{
CopyCost = 2 * numberOfCopies;
}
Better, use this code:
int TotalCost;
if (amountOfCopies > 100)
{
TotalCost = (amountOfCopies - 100) * (CopyCost - discount) + 100 * CopyCost;
}
else
{
TotalCost = amountOfCopies * CopyCost;
}
Console.WriteLine("The total cost for your copies is: {0} ", TotalCost);
Or if you prefer a one-liner:
price = (copies * 2) - Math.Max(copies - 100, 0);

What is the most efficient way to truncate a number for a specific accuracy?

What is the most efficient way to truncate a number for a specific accuracy?
In a DateTime, Milliseconds are always comprised between 0 and 999 so you don't have anything to do.
int ms = Convert.ToInt32(
Convert.ToString(DateTime.Now.Millisecond).Substring(0, 3));
or
double Length = Math.Pow(10, (DateTime.Now.Millisecond.ToString().Length - 3));
double Truncate = Math.Truncate((double)DateTime.Now.Millisecond / Length);
EDIT:
After running both the below on the code I will post, the double method works well due to reuse of variables. Over an iteration of 5,000,000 DateTime.Now's (in which many will be skipped by both checks), the SubString() method took 9598ms, and the Double method took 6754ms.
EDIT#2: Edited in * 1000 into tests to make sure the iterations are running.
Code used to test as follows:
Stopwatch stop = new Stopwatch();
stop.Start();
for (int i = 0; i < 5000000; i++)
{
int MSNow = DateTime.Now.Millisecond * 1000;
if (MSNow.ToString().Length > 2)
{
int ms = Convert.ToInt32(
Convert.ToString(MSNow).Substring(0, 3));
}
}
stop.Stop();
Console.WriteLine(stop.ElapsedMilliseconds);
stop = new Stopwatch();
stop.Start();
for (int i = 0; i < 5000000; i++)
{
int MSNow = DateTime.Now.Millisecond * 1000;
int lengthMS = MSNow.ToString().Length;
if (lengthMS > 2)
{
double Length = Math.Pow(10, (lengthMS - 3));
double Truncate = Math.Truncate((double)MSNow / Length);
}
}
stop.Stop();
Console.Write(stop.ElapsedMilliseconds);
Console.ReadKey();
Math.Floor(num * Math.Pow(10, x) + 0.5) / Math.Pow(10, x)
Where x your precision

Categories

Resources