Using the mod operator to decrease value in a textbox - c#

Okay so I have created this vending machine application form and I am having problems getting rid of the change. The machine has 50 10p's in at the start of the day. A fizzy drink costs 40p, so, if the user puts in 50p, he will get change back of 10p. I have a textbox showing the amount of 10p's in the machine, so at the start, 50, after he puts in 50p it will be 55. However, now that he has to get 10p change (I have a release change button), I want the amount of 10p's in the textbox to go to 54...any ideas? I tried using the mod operator but wasn't sure how to use it:
decimal change = decimal.Parse(txtChange.Text)
if (change % 10 > 1)
{
int tenPenny = int.Parse(txt_BoxTenPenny.Text);
int totalTenPen = tenPenny - 1;
txt_BoxTenPenny.Text = totalTenPen.ToString();
}
I know this isn't right, when I was doing research, they were using the % operator and using the number 10 as the numerator..so..I got a bit lost. Any suggestions would be great!

If you're trying to determine how many 10 pennies the user is owed, this is calculated using:
int tenPennies = change / 10
As opposed to the modulus (%) operator, so:
decimal change = decimal.Parse(txtChange.Text)
int tenPenny = int.Parse(txt_BoxTenPenny.Text);
int totalTenPen = tenPenny - change / 10 ;
txt_BoxTenPenny.Text = totalTenPen.ToString();
Hope that helps!

Something like that:
decimal change = decimal.Parse(txtChange.Text)
if (change % 10 > 0)
{
int tenPenny = int.Parse(txt_BoxTenPenny.Text);
int totalTenPen = tenPenny - (change % 10);
txt_BoxTenPenny.Text = totalTenPen.ToString();
}
But is supposed that before that, you have added the 50p the users puts into machine in the txt_BoxTenPenny.

The modulo operator (%) returns the remainder of a division operation. For example, 23 MOD 10 = 3.
In this case I believe you want integer division, or the Floor. That is, you want to divide and throw away the remainder.
Since you are using decimal, I presume change will contain 0.10 for 10p. In that case, try the following:
//calculate the number of 10p coins you will get for change
var tenPenniesChange = (int)Math.Floor(change / 0.10m);
if(tenPenniesChange > 0)
txt_BoxTenPenny.Text = (int.Parse(txt_BoxTenPenny.Text) - tenPenniesChange).ToString();
change -= tenPenniesChange * 0.10;
Note the use of the Math.Floor function. If you had change = 0.13 you will get tenPenniesChange = 1. After the subtraction, you will then get change = 0.03.

This may be of some use:
Issuing vending machine change: Using C# to recursively build and search a tree

Related

c# large fractional decimal split

My Requirement is Fractional Amount FIrst 2 decimal part add customer bank account and others fractional part add in dispute wallet account .
var amount = 40.235667745465465
I want to convert it 2 different variable
var customerBalance = // ??? - should be 40.23
var disputeBalance = amount - customerBalance
How can I do calculate the step marked ??? ?
This will work fine.
var firstAmount = Math.Floor(amount / 0.01) / 100 ;
var secondVariable = amount - firstAmount;
You probably want:
var firstAmount = Math.Round(amount, 2);
but note that this can round up as well as down; you may want to check whether secondVariable comes out negative, and if so: compensate.
Another way to look at it is to multiply by 100 and take the integer/decimal parts (hint: Math.Floor), then divide by 100 again.
If you are looking for a string, then it can be:
string secondVariableAsString = string.Format("{0:0.00}", secondVariable);
Another is:
Math.Truncate(100 * secondVariable) / 100;
However, this will cause overflow for large numbers.

multiplicative persistence - recursion?

I'm working on this:
Write a function, persistence, that takes in a positive parameter num
and returns its multiplicative persistence, which is the number of
times you must multiply the digits in num until you reach a single
digit.
For example:
persistence(39) == 3 // because 3*9 = 27, 2*7 = 14, 1*4=4
// and 4 has only one digit
persistence(999) == 4 // because 9*9*9 = 729, 7*2*9 = 126,
// 1*2*6 = 12, and finally 1*2 = 2
persistence(4) == 0 // because 4 is already a one-digit number
This is what I tried:
public static int Persistence(long n)
{
List<long> listofints = new List<long>();
while (n > 0)
{
listofints.Add(n % 10);
n /= 10;
}
listofints.Reverse();
// list of a splited number
int[] arr = new int[listofints.Count];
for (int i = 0; i < listofints.Count; i++)
{
arr[i] = (int)listofints[i];
}
//list to array
int pro = 1;
for (int i = 0; i < arr.Length; i++)
{
pro *= arr[i];
}
// multiply each number
return pro;
}
I have a problem with understanding recursion - probably there is a place to use it. Can some1 give me advice not a solution, how to deal with that?
It looks like you've got the complete function to process one iteration. Now all you need to do is add the recursion. At the end of the function call Persistence again with the result of the first iteration as the parameter.
Persistence(pro);
This will recursively call your function passing the result of each iteration as the parameter to the next iteration.
Finally, you need to add some code to determine when you should stop the recursion, so you only want to call Persistence(pro) if your condition is true. This way, when your condition becomes false you'll stop the recursion.
if (some stop condition is true)
{
Persistence(pro);
}
Let me take a stab at explaining when you should consider using a recursive method.
Example of Factorial: Factorial of n is found by multiplying 1*2*3*4*..*n.
Suppose you want to find out what the factorial of a number is. For finding the answer, you can write a foreach loop that keeys multiplying a number with the next number and the next number until it reaches 0. Once you reach 0, you are done, you'll return your result.
Instead of using loops, you can use Recursion because the process at "each" step is the same. Multiply the first number with the result of the next, result of the next is found by multiplying that next number with the result of the next and so on.
5 * (result of rest)
4 * (result of rest )
3 * (result of rest)
...
1 (factorial of 0 is 1).---> Last Statement.
In this case, if we are doing recursion, we have a terminator of the sequence, the last statement where we know for a fact that factorial of 0 = 1. So, we can write this like,
FactorialOf(5) = return 5 * FactorialOf(4) = 120 (5 * 24)
FactorialOf(4) = return 4 * FactorialOf(3) = 24 (4 * 6)
FactorialOf(3) = return 3 * FactorialOf(2) = 6 (3 * 2)
FactorialOf(2) = return 2 * FactorialOf(1) = 2 (2 * 1)
FactorialOf(1) = return 1 * FactorialOf(0) = 1 (1 * 1)
FactorialOf(0) = Known -> 1.
So, it would make sense to use the same method over and over and once we get to our terminator, we stop and start going back up the tree. Each statement that called the FactorialOf would start returning numbers until it reaches all the way to the top. At the top, we will have our answer.
Your case of Persistence
It calls for recursive method as well as you are taking the result and doing the same process on it each time.
Persistence(39) (not single) = return 1 + Persistence(3 * 9 = 27) = 3
Persistence(27) (not single) = return 1 + Persistence(2 * 7 = 14) = 2
Persistence(14) (not single) = return 1 + Persistence(1 * 4 = 4) = 1
Persistence(4) (single digit) = Known -> 0 // Terminator.
At the end of the day, if you have same process performed after each calculation / processing with a termination, you can most likely find a way to use recursion for that process.
You definitely can invoke your multiplication call recursively.
You will need initial sate (0 multiplications) and keep calling your method until you reach your stop condition. Then you return the last iteration you've got up to as your result and pass it through all the way up:
int persistence(int input, int count = 0) {} // this is how I would define the method
// and this is how I see the control flowing
var result = persistence(input: 39, count: 0) {
//write a code that derives 27 out of 39
//then keep calling persistence() again, incrementing the iteration count with each invocation
return persistence(input: 27, count: 1) {
return persistence(input: 14, count: 2) {
return persistence(input: 4, count: 3) {
return 3
}
}
}
}
the above is obviously not a real code, but I'm hoping that illustrates the point well enough for you to explore it further
Designing a simple recursive solution usually involves two steps:
- Identify the trivial base case to which you can calculate the answer easily.
- Figure out how to turn a complex case to a simpler one, in a way that quickly approaches the base case.
In your problem:
- Any single-digit number has a simple solution, which is persistence = 1.
- Multiplying all digits of a number produces a smaller number, and we know that the persistence of the bigger number is greater than the persistence of the smaller number by exactly one.
That should bring you to your solution. All you need to do is understand the above and write that in C#. There are only a few modifications that you need to make in your existing code. I won't give you a ready solution as that kinda defeats the purpose of the exercise, doesn't it. If you encounter technical problems with codifying your solution into C#, you're welcome to ask another question.
public int PerRec(int n)
{
string numS = n.ToString();
if(numS.Length == 1)
return 0;
var number = numS.ToArray().Select(x => int.Parse(x.ToString())).Aggregate((a,b) => a*b);
return PerRec(number) + 1;
}
For every recursion, you should have a stop condition(a single digit in this case).
The idea here is taking your input and convert it to string to calculate that length. If it is 1 then you return 0
Then you need to do your transformation. Take all the digits from the string representation(in this case from the char array, parse all of them, after getting the IEnumerable<int>, multiply each digit to calculate the next parameter for your recursion call.
The final result is the new recursion call + 1 (which represents the previous transformation)
You can do this step in different ways:
var number = numS.ToArray().Select(x => int.Parse(x.ToString())).Aggregate((a,b) => a*b);
convert numS into an array of char calling ToArray()
iterate over the collection and convert each char into its integer representation and save it into an array or a list
iterate over the int list multiplying all the digits to have the next number for your recursion
Hope this helps
public static int Persistence(long n)
{
if (n < 10) // handle the trivial cases - stop condition
{
return 0;
}
long pro = 1; // int may not be big enough, use long instead
while (n > 0) // simplify the problem by one level
{
pro *= n % 10;
n /= 10;
}
return 1 + Persistence(pro); // 1 = one level solved, call the same function for the rest
}
It is the classic recursion usage. You handle the basic cases, simplify the problem by one level and then use the same function again - that is the recursion.
You can rewrite the recursion into loops if you wish, you always can.

Getting the nearest value that returns true on a bool

If I wanted to get the nearest value to a number, but that value also has to return true on a bool called IsMultipleOf7 which returns true on numbers that are multiples of 7.
For example, I have a int x = 523. So the nearest multiple of 7 is 525, so my bool would return true 525.
How can I get that number?
This function will return the closest multiple of 7 or the number itself if it is a multiple of 7
public int GetClosestNumber(int number, out bool isMultipleOf7)
{
// if the number is a multiple of 7 isMultipleOf7 is set to true
isMultipleOf7 = number%7 == 0;
if (isMultipleOf7)
{
// if it's a multiple of 7 then the closest one is the number itself
return number;
}
// if it's not a multiple of 7 then try find the closest.
var lower = number - (number % 7);
var upper = (number + 7) - (number %7);
var diffL = Math.Abs(number - lower);
var diffU = Math.Abs(number - upper);
return diffL > diffU ? upper : lower;
}
And here's a usage example:
bool IsMultipleOf7;
// Following line will output: Closest multiple of 7 is: 525
Console.WriteLine("Closest multiple of 7 is: {0}",
GetClosestNumber(523, out IsMultipleOf7));
// Following line will output: The number itself is not a multiple of 7"
Console.WriteLine("The number itself is {0} a multiple of 7",
IsMultipleOf7 ? string.Empty: "not");
Live demo is also available here
int x = 523;
while ((int)x/7!=(decimal)x/7){
x++;
}
return x;
int x = 523;
int result = ((x / 7) + 1) * 7;
You may need a more complex formula, if your number is dividable by 7 and should stay the same number. Or maybe you have simplified your problem too much?
There are two ways I can think of. The first is the brute force method I commented about. If you start with the number x, test it. If it works, hooray! If not, try adding one to x and test. Then subtract one from x and test. Then do this with two, and three, testing up and down at the same time. Once your test returns true, you have located (one of) the closest number(s) that work. This method is a general one and will work with any test function.
Because we know you are using IsMultipleOf7 as the test, a smarter method could be possible. Imagine the time it would take if your test was instead IsMultipleOf999999999! So many numbers might have to tested before hitting the closest. Instead, some math can be used. First, compute x modulo 7 (for IsMultipleOf7), written x % 7 in C(++). This value tells you how far x is from the largest multiple of 7 LESS than x. If this value is 0, x is a multiple of 7. If the value is 1, 2 or 3, x minus the value is the closest multiple. If the value is 4, 5 or 6, x plus the difference to make 7 (7 - value) is the closest multiple.
Some pseudo-code:
x = 523
value = x modulo 7
if(value == 0):
return x
if(value < 4): // that is, less than half of 7
return x - value
otherwise
return x + (7 - value)
x=7*Math.Round(((float)x)/7.0)
^Simplest solution right there ;)
No need for all of this looping and stuff.
divide by 7, if the decimals are less than 0.5 then the nearest denominator is floored, else ceiling. Round() does that for you, then just multiply your new int by 7 to create a number evenly divisible by 7 (since it was an int being multiplied by 7). It will get the closest value above or below. No need for bool at all. Make sure you cast float onto x so that it can be divided by 7 without causing flooring with integer logic.

Enter a code branch every ten percent till 100 percent

I can think of some very convoluted methods with loops and nested loops to solve this problem but I'm trying to be more professional than that.
My scenario is that I need to enter a section of code every ten percent but it isn't quite working as expected. It is entering the code about every percent which is due to my code but I lack the knowledge to know how to change it.
int currentPercent = Math.Truncate((current * 100M) / total);
//avoid divide by zero error
if (currentPercent > 0)
{
if (IsDivisible(100, currentPercent))
{
....my code that works fine other than coming in too many times
}
}
Helper referenced above where the trouble is:
private bool IsDivisible(int x, int y)
{
return (x % y) == 0;
}
So obviously it works as it should. Mod eliminates currentPercent of 3 but 1 & 2 pass when really I don't want a true value until currentPercent = 10 and then not again till 20...etc.
Thank you and my apologies for the elementary question
Mod will only catch exact occurrences of your interval. Try keeping track of your next milestone, you'll be less likely to miss them.
const int cycles = 100;
const int interval = 10;
int nextPercent = interval;
for (int index = 0; index <= cycles; index++)
{
int currentPercent = (index * 100) / cycles;
if (currentPercent >= nextPercent)
{
nextPercent = currentPercent - (currentPercent % interval) + interval;
}
}
I might misunderstand you, but it seems like you're trying to do something extremely simple more complex than it needs to be. What about this?
for (int i = 1; i <= 100; i++)
{
if (i % 10 == 0)
{
// Here, you can do what you want - this will happen
// every ten iterations ("percent")
}
}
Or, if your entire code enters from somewhere else (so no loop in this scope), the important part is the i % 10 == 0.
if (IsDivisible(100, currentPercent))
{
....my code that works fine other than coming in too many times
}
try changing that 100 to a 10. And I think your x and y are also backwards.
You can try a few sample operations using google calculator.
(20 mod 10) = 0
Not sure if I fully understand, but I think this is what you want? You also reversed the order of modulo in your code (100 mod percent, rather than the other way around):
int currentPercent = current * 100 / total;
if (currentPercent % 10 == 0)
{
// your code here, every 10%, starting at 0%
}
Note that code this way only works properly if you are guaranteed to hit every percentage-mark. If you could, say, skip from 19% to 21% then you'll need to keep track of which percentage the previous time was to see if you went over a 10% mark.
try this:
for (int percent = 1; percent <= 100; percent++)
{
if (percent % 10 == 0)
{
//code goes here
}
}
Depending on how you increment your % value, this may or may not work % 10 == 0. For example jumping from 89 to 91 % would effectively skip the code execution. You should store last executed value, 80 in this case. Then check if interval is >= 10, so 90 would work, as well as 91.

Multi-threading Report Progress Not Working

I've recently started working with multi-threaded Winform applications and have run up against a problem I don't understand.
Basically, when I try to have a background worker report its progress and that progress comes from a calculation, it is always zero.
//making background worker
BackgroundWorker myJanitor = new BackgroundWorker();
myJanitor.WorkerSupportsCancellation = true;
myJanitor.WorkerReportsProgress = true;
myJanitor.DoWork += new DoWorkEventHandler(cleanContactList);
myJanitor.ProgressChanged += new ProgressChangedEventHandler(myCleaningWorker_ProgressChanged);
myJanitor.RunWorkerAsync();
The 'cleanContactList' method loops through a DataGridView's rows, during which I try something like this:
int percentComplete = (myRow.Index / contactGridView.Rows .Count ) * 100;
(sender as BackgroundWorker).ReportProgress(percentComplete);
Frustratingly, percentComplete will ALWAYS be zero. If I debug it I can see that there is an actual calculation occurring (e.g. [2000/10000]*100) but the result is always zero.
What am I missing here? If I replace the calculation with, say, a Random.Next(0,100) call it updates fine.
Try index * 100/count. I think you're dividing two ints leading to 0 then multiplying by 100.
For example, this:
int index = 50;
int count = 100;
int percent = index/count * 100;
int percent2 = index * 100/count;
Console.WriteLine("{0} & {1}", percent, percent2);
Outputs 0 & 50.
[2000/10000]*100) but the result is always zero
C# 101 for beginners. Actually more programming - it is the same in most languages that know variable types.
Operations happen on the alrgest most precice variable type involved.
2000 (integer) / 10000 (integer) is aninteger result rounded = 0
I suggest you FIRST multiply, THEN divide. Or choose a different variable type either in the variables, or in the formula (i.e. [(float)2000 will convert the whole formulat to use floats.

Categories