I was trying to create a program that will display the imputed amount and the number of $10 and $1 notes that an ATM can dispense but it will not display correct amount of $1 notes.
int amount = int.Parse(txtAmount.Text);
int tenNotes=0, oneNotes=0;
CalculateNotes(amount, ref tenNotes, ref oneNotes);
private void CalculateNotes( int amount, ref int tenNotes, ref int OneNotes)
{
tenNotes = amount /10;
OneNotes = amount - amount % 10;
rtbDisplay.AppendText("Ammount is " + amount + "Ten notes is" + tenNotes + "One notes is" + OneNotes);
}
This is the output I have tried different method of calculation for $1 notes but it does not work.
Am I supposed to use out instead of ref or is there an error in my calculation? Thank you for any help.
You should change this line
OneNotes = amount - amount % 10;
to this one
OneNotes = amount - (tenNotes * 10);
and please reconsider your using of int.Parse to read the input from the textbox. If your user types an invalid integer value you get an exception. This exception could be easily avoided using Int32.TryParse
Finally, I suggest also to use the out keyword for your parameters instead of ref.
See When to use ref vs out
An alternate to the solution that Steve gave, you could also do the following:
Change:
OneNotes = amount - amount % 10;
to:
OneNotes = amount % 10;
Additional Alternate -
It should be noted that what you are trying to do is already a pre-existing function in the System.Math library. As such, you can replace the following code block:
tenNotes = amount /10;
OneNotes = amount - amount % 10;
with:
tenNotes = Math.DivRem(amount, 10, out OneNotes);
Related
public static int addIntNumbers()
{
int input = int.Parse(Console.ReadLine());
int sum = 0;
while (input !=0)
{
sum += input % 10;
input /= 10;
Console.WriteLine(sum);
}
return sum;
}
I don't understand this syntax: After the while condition, sum += input % 10, which basically means sum = sum(which is 0) + input % 10, so lets say I input 24 so the sum of this should be 4, I think ?
And then the second line which I have no idea what it is even doing.
Any suggestions ?
The best way might be to add comments. However I can already tell that whoever wrote this, did not know what he as doing. For starters, there were not comments, the naming is abysmal and the I/O is actually handeled inside the function.
//The name is not right. This is not a proper sum function
//I think it is getting a sum of all digits in the input
public static int addIntNumbers()
{
//Get a input from the user, parse it to int
//That really belons outside. Just the int in per argument
int input = int.Parse(Console.ReadLine());
//Initialize sum to 0
int sum = 0;
//Input is also used as sort of "running variable".
//The loop will break if input reaches 0
while (input !=0)
{
//sum = sum + input % 10
//It tries to divide input by 10, get's the rest, then adds that rest to sum
sum += input % 10;
//Divide input by 10. Note that all decimal parts will be dropped
//That means it will reach 0 invariably
input /= 10;
//Output the current sum for debugging
Console.WriteLine(sum);
}
//The function returns
return sum;
}
Your code calculates digit-by-digit sum of an integer (the sum is positive if input is positive, negative if input is negative).
If you are a C# beginner, this might help you:
while (input !=0)
{
sum = sum + (input % 10); //sum = sum + remainder of division by ten (separation of least significant digit)
input = input / 10; //input is integer-divided by ten, which results in discarding of the least significant digit
Console.WriteLine(sum);
}
If you don't understand, get familiar with a difference between
4/6
and 4.0/6.
The first one is integer division, the other is floating point division.
Some things to help you understand what's going on here:
First, assuming you're in Visual Studio, you can set a break point in your code by clicking to the left of the line number, in the margin. A red dot will show up and when your code hits that point, it will pause. While paused, you can look at the "Locals" tab or hover over variable names in your code to see what values are at that point in time. You can then use F10 to step forward one line at a time and see how things change.
Second, the /= operator is similar to the += operator, except with division. So, "x /= 10" is exactly the same as "x = x / 10".
This program is adding up each digit of the number you type in by getting the ones digit, adding it to sum, then dividing the number by 10 to get rid of the old ones digit.
So I'm a complete newb to unity and c# and I'm trying to make my first mobile incremental game. I know how to format a variable from (e.g.) 1000 >>> 1k however I have several variables that can go up to decillion+ so I imagine having to check every variable's value seperately up to decillion+ will be quite inefficient. Being a newb I'm not sure how to go about it, maybe a for loop or something?
EDIT: I'm checking if x is greater than a certain value. For example if it's greater than 1,000, display 1k. If it's greater than 1,000,000, display 1m...etc etc
This is my current code for checking if x is greater than 1000 however I don't think copy pasting this against other values would be very efficient;
if (totalCash > 1000)
{
totalCashk = totalCash / 1000;
totalCashTxt.text = "$" + totalCashk.ToString("F1") + "k";
}
So, I agree that copying code is not efficient. That's why people invented functions!
How about simply wrapping your formatting into function, eg. named prettyCurrency?
So you can simply write:
totalCashTxt.text = prettyCurrency(totalCashk);
Also, instead of writing ton of ifs you can handle this case with logarithm with base of 10 to determine number of digits. Example in pure C# below:
using System.IO;
using System;
class Program
{
// Very simple example, gonna throw exception for numbers bigger than 10^12
static readonly string[] suffixes = {"", "k", "M", "G"};
static string prettyCurrency(long cash, string prefix="$")
{
int k;
if(cash == 0)
k = 0; // log10 of 0 is not valid
else
k = (int)(Math.Log10(cash) / 3); // get number of digits and divide by 3
var dividor = Math.Pow(10,k*3); // actual number we print
var text = prefix + (cash/dividor).ToString("F1") + suffixes[k];
return text;
}
static void Main()
{
Console.WriteLine(prettyCurrency(0));
Console.WriteLine(prettyCurrency(333));
Console.WriteLine(prettyCurrency(3145));
Console.WriteLine(prettyCurrency(314512455));
Console.WriteLine(prettyCurrency(31451242545));
}
}
OUTPUT:
$0.0
$333.0
$3.1k
$314.5M
$31.5G
Also, you might think about introducing a new type, which implements this function as its ToString() overload.
EDIT:
I forgot about 0 in input, now it is fixed. And indeed, as #Draco18s said in his comment nor int nor long will handle really big numbers, so you can either use external library like BigInteger or switch to double which will lose his precision when numbers becomes bigger and bigger. (e.g. 1000000000000000.0 + 1 might be equal to 1000000000000000.0). If you choose the latter you should change my function to handle numbers in range (0.0,1.0), for which log10 is negative.
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
I've figured out how to compare 2 text boxes and count how many words are the same in each one and how many are different but I was wondering instead of showing exactly how many are the same and how many are different could I calculate the percentage of difference between them?
For those who I confused, if i wrote this entire message again under this post and changed a few words and maybe removed some I could get feedback from the program telling me the difference is 14% or so...
You can get words by using string.Split:
String[] words1 = Textbox1.Text.Split();
String[] words2 = Textbox2.Text.Split();
You can use Linq to compare both:
var sameWordsInBoth = words1.Intersect(words2);
int count1 = sameWordsInBoth.Count();
var inTxt1ButNotInTxt2 = words1.Except(words2);
int count2 = inTxt1ButNotInTxt2.Count();
var inTxt2ButNotInTxt1 = words2.Except(words1);
int count3 = inTxt2ButNotInTxt1.Count();
To get the percentage you just have to count the total words(f.e. words1.Length) and compare that to the other counts.
For example:
double sameWordPercentage = (1.0 * count1 / words1.Length) * 100;
Since you said you already have the amount of unique words, and dont need explanation on how to get them:
double UniqueWordCount = 71;
double TotalWordCount = 231;
double Percentile = (UniqueWordCount/TotalWordCount)*100;
Answer : 30.7359.... %
If you want to round it
Math.Round(Percentile,2)
Answer : 30.74 %
How to get the first two numbers of an integer and the last two in c#.
For example:
int complete = 1935;
how to make,
int firtTwo = 19;
and
int secondTwo = 35;
Please help.
Is it always a four-digit positive value? If so, I'd go for:
int hundreds = complete / 100;
int tensAndUnits = complete % 100;
If it's any arbitrary number, so you'd want "935" to be "93" and "35" you might as well use string operations:
string text = complete.ToString();
int first = int.Parse(text.Substring(0, 2));
int last = int.Parse(text.Substring(text.Length - 2, 2));
(Note that this will blow up for single-digit values...)
It would help if you could say what this is meant to be for though.