How do I combine two integers in C#? - c#

Let's say I have the following code:
int digit1 = 1;
int digit2 = 3;
and I need to combine the two integers, resulting in a floating-point number equal, in this case, to 13.0f. This is probably easy, as I'm new to C# and learning it from a book, but how is it done?
Example:
int digit1 = 3;
int digit2 = 6;
float result = combine_integers (digit1, digit2);
// result = 36
NOTE:
I don't actually need a function. I just did that for the sake of the example.

float combine_integers (int digit1, int digit2)
{
return 10*digit1 + digit2;
}
Example
combine_integers(1, 3) ==>
10 * 1 + 3 ==>
10 + 3 ==>
13
combine_integers(3, 6) ==>
10 * 3 + 6 ==>
30 + 6 ==>
36

If your integers are single digits, then abelenky's answer above is going to do it quickest for you. If they're not single digits, then you could do string.Format() as above, but there's also a couple of edge cases that aren't covered, such as negative values or both values being 0.
The string operations above could produce results such as "00", "5-1", or throw an error for not being able to parse the string result. In the case of {5,-1}, you could end up with 49.
What I would do is cover my bases and assume that if you use a negative number, you want the absolute value. This code also covers the base case of single digits, but gives you some flexibility so that combine_integers(12,34) returns 1234.0f.
static float combine_integers (int digit1, int digit2)
{
int checker = Math.Abs(digit2);
int result = Math.Abs(digit1);
do
{
result *= 10;
checker /= 10;
} while(checker>0);
result += Math.Abs(digit2);
return (float)result;
}

private static float combine_integers(int a, int b)
{
return float.Parse(a.ToString() + b.ToString());
}
https://dotnetfiddle.net/M9Bpwt

Try this code:
int digit1 = 3;
int digit2 = 6;
string concat = string.Format("{0}{1}", digit1, digit2);
float result = float.Parse(concat);

Related

How do I divide integers and not get a 1

Just a simple console program in c#. The answer is always 1, but I want to get the right answer and the answer to always be an integer, nothing but whole numbers here.
Console.Write("Ange dagskassa (kr): ");
string inlasning = Console.ReadLine();
int dagskassa = int.Parse(inlasning);
Console.Write("Ange nuvarande lunchpris (kr): ");
string inlasning2 = Console.ReadLine();
int lunchpris = int.Parse(inlasning);
double antalGaster = dagskassa / lunchpris;
Console.WriteLine("Antal gäster: " + antalGaster + "st.");
The problem here is that you're converting the same number twice, to two different variables, and then dividing them, so the answer will always be 1:
int dagskassa = int.Parse(inlasning);
int lunchpris = int.Parse(inlasning); // You're parsing the same input as before
To resolve this, convert the second input for the lunch price:
int dagskassa = int.Parse(inlasning2); // Parse the *new* input instead
You'll need to cast your ints to double in order for the above to work. For example,
int i = 1;
int j = 2;
double _int = i / j; // without casting, your result will be of type (int) and is rounded
double _double = (double) i / j; // with casting, you'll get the expected result
In the case of your code, this would be
double antalGaster = (double) dagskassa / lunchpris;
To round to the lowest whole number for a head count, use Math.Floor()
double antalGaster = Math.Floor((double) dagskassa / lunchpris);

C# - Class that uses ILists to store huge integers without BigInt. Can't figure out how to use CompareTo and Int.TryParse to +, -, and * two Lists

I've been working on an assignment and I'm a beginner to C#. I have to implement a program that's similar to what BigInt can do: perform addition, subtraction, or multiplication with two absurdly large values (without actually using the BigInt library). I was told to use CompareTo and that it would make creating the add, subtract, and multiply methods easy, but I have no clue how to implement CompareTo. I don't even know if my class is implemented correctly or if I am missing something important.
Here is my code:
public class HugeInt
{
char sign;
public IList<int> theInt = new List<int>();
public string ToString(IList<int> theInt)
{
string bigInt = theInt.ToString();
return bigInt;
}
public HugeInt CompareTo(HugeInt num1)
{
int numParse;
string number = ToString(theInt); /// I did this to convert the List into a string
for(int i = 0; i < number.Length; i++)
{
bool temp = Int32.TryParse(number, out numParse); /// Supposed to change each index of the string to a separate integer (not sure how to properly do this)
/// These are *supposed to* perform operations on two HugeInts ///
num1.plus(numParse, num1);
num1.minus(numParse, num1);
num1.times(numParse, num1);
}
return num1;
}
I'm not here to ask for all the answers for this assignment, I've just been working on this for hours now and can't figure out what I'm doing wrong -- I have already done a lot of google searching. Thanks in advance for all advice and help!
To write such a class, it requires you know a little bit about how to do math by hand. For example, when adding two numbers, you start by adding their least significant digits. If the result is greater than 9, you have to carry a 1 to the next digit (explanation). Then you continue to the next digit.
Now, here is my take on it. I want to save the "huge int" as a list of digits starting from the least significant digit. Then I implement the Plus method as described above. I can compare two "huge ints" by looking at the number of digits. The number with the most digits is the largest. In the case the number of digits are the same, I will need to compare each digit one-by-one, starting from the most significant digit.
The below is just something to get you started. It only handles positive integers and has Plus and CompareTo methods. Be aware there are plenty of corner cases that I have not taken care of.
It can be used like this:
var num1 = new HugeInt("11112222333399998888777123123");
var num2 = new HugeInt("00194257297549");
Console.WriteLine(num1.Plus(num2).ToString()); // Writes 11112222333399999083034420672
Console.WriteLine(num1.CompareTo(num2)); // Writes -1 since num1 > num2
Here is the class:
public class HugeInt
{
// The array that contains all the digits of the number. To create a new number, you do not change this array but instead you create a new instance of HugeInt.
// The first digit is the least significant digit.
private readonly int[] digits;
public HugeInt(string number)
{
// Trim off the leading zeros
number = number.TrimStart('0');
if (number == "")
number = "0";
// Convert to digit array with the least significant digit first
digits = number.ToCharArray().Select(c => int.Parse(c.ToString())).Reverse().ToArray();
}
public HugeInt(IList<int> digits)
{
// Trim off the leading zeros
var d = digits.ToList();
while (d.Count > 1 && d.Last() == 0)
d.RemoveAt(d.Count - 1);
// Convert to digit array with the least significant digit first
this.digits = d.ToArray();
}
public HugeInt Plus(HugeInt num)
{
// Add two positive integers by adding each digit together, starting with the least significant digit.
var result = new List<int>();
int carry = 0;
for (var i = 0; i < this.digits.Length || i < num.digits.Length; i++)
{
var digit1 = i < this.digits.Length ? this.digits[i] : 0;
var digit2 = i < num.digits.Length ? num.digits[i] : 0;
var digitResult = digit1 + digit2 + carry;
carry = 0;
if (digitResult >= 10)
{
digitResult -= 10;
carry = 1;
}
result.Add(digitResult);
}
if (carry > 0)
result.Add(carry);
return new HugeInt(result);
}
public int CompareTo(HugeInt num)
{
// First compare by length of number
if (this.digits.Length > num.digits.Length)
return -1;
else if (this.digits.Length < num.digits.Length)
return 1;
else
{
// If lengths are equal, then compare each digit - starting with the most significant digit.
for (var i = this.digits.Length - 1; i >= 0; i--)
{
var cmp = this.digits[i].CompareTo(num.digits[i]);
if (cmp != 0)
return cmp;
}
return 0;
}
}
public override string ToString()
{
return String.Join("", digits.Reverse());
}
}

Calculate checksum in C#

numbers[i] = numbers[i] * 2;
if (numbers[i] >= 10)
{
string t = numbers[i].ToString();
Console.WriteLine(t[0] + " plus " + t[1]+" = "+quersumme(t).ToString());
numbers[i] = Convert.ToInt32(t[0]) + Convert.ToInt32(t[1]);
}
public int quersumme(string n)
{
return n[0] + n[1];
}
The function returns 101 when I enter 7. But 7 * 2 = 14 and quersumme should do 1+4 = 5
t[0] is the character '1', and t[1] is the character '4', which is translated to 49 + 52, hence 101. Check out an ASCII chart to see what I'm talking about.
You could try using the Char.GetNumericValue() function:
return (int)Char.GetNumericValue(n[0]) + (int)Char.GetNumericValue(n[1]);
You're currently summing the Unicode code points - '1' is 49, and '4' is 52, hence the 101. You want to take the digit value of each character.
If you know that the digits will be in the range '0'-'9', the simplest way of doing that is just to subtract '0' and to use the LINQ Sum method to sum each value:
public int SumDigits(string n)
{
return n.Sum(c => c - '0');
}
Or you could use Char.GetNumericValue(), but that returns double because it also copes with characters such as U+00BD: ½.
Try converting n[0] and n[1] to separate int32's in your quersomme function
You are doing string concatenation in quesumme method.
Should be:
public int quersumme(string n)
{
return (int)Char.GetNumericValue(n[0]) + (int)Char.GetNumericValue(n[1]);
}
It looks to me like you are trying to enumerate the digits in an int.
Try this to avoid slow and cumbersome parsing and conversion. (Its all relative, I haven't tested performance.)
static IEnumerable<int> EnumerateDigits(int value, int baseValue = 10)
{
while (value > 0)
{
yield return value % baseValue;
value = value / baseValue
}
}
Then, if you want to switch the order into an array
var t = EnumerateDigits(numbers[i]).Reverse().ToArray();
But, if you just want to sum the digits.
var checksum = EnumerateDigits(numbers[i]).Sum()

how to use the round maths function in asp.net?

I am use the textbox value like 1455.23, use the round function my output is 0000145523 but customer not enter float values like 1234 my output is 0000123400 pls give me suggestion
my code is format.cs
public bool formatAmount(float flAmount, out string strOutput)
{
bool bval = false;
float rounded = (float)Math.Round(flAmount, 2);
if(rounded!=null)
{
flAmount = flAmount * 100;
strOutput = Convert.ToString(flAmount);
bVal = true;
}
return bVal;
}
In my asp page code like this
string ods;
float a = Convert.Todecimal(txtSSA.Text);
string sss = oclsUtility.formatAmount(a, out ods);
I am assuming you want to ignore the multiplication of 100 part in case the fractional value is not there.
So 1234 in your case is essentially 1234.00 and you need to avoid the 0000123400
float flAmount = 15F;
float rounded = (float)Math.Round(flAmount, 2);
double fractionalval = (rounded - Math.Floor(rounded)) * 100;
if(fractionalval > 0)
flAmount = flAmount * 100;
After this i presume rest might work and pad it to 10 length string.
This would skip the multiplication if there are fractional parts, hope this is what you need else please edit for additional information.
If I'm understanding you, you need to keep leading 0 if user input is float and if not removes them. You can try this:
int number;
bool result = Int32.TryParse(rounded, out number);
if (result)
{
// Your number will contain the number with no leading 0
}
else
{
// Then you have a float.
}

Modulo from very large int C#

I'm having a problem with modulo from int which has 31 chars. It seems to bug out on
Int64 convertedNumber = Int64.Parse(mergedNumber); with Value was either too large or too small for an Int64. (Overflow Exception). How to fix it so that modulo doesn't bug out ?
class GeneratorRachunkow {
private static string numerRozliczeniowyBanku = "11111155"; // 8 chars
private static string identyfikatorNumeruRachunku = "7244"; // 4 chars
private static string stalaBanku = "562100"; // 6 chars
public static string generator(string pesel, string varKlientID) {
string peselSubstring = pesel.Substring(pesel.Length - 5); // 5 chars (from the end of the string);
string toAttach = varKlientID + peselSubstring;
string indywidualnyNumerRachunku = string.Format("{0}", toAttach.ToString().PadLeft(13, '0')); // merging pesel with klient id and adding 0 to the begining to match 13 chars
string mergedNumber = numerRozliczeniowyBanku + identyfikatorNumeruRachunku + indywidualnyNumerRachunku + stalaBanku; // merging everything -> 31 chars
Int64 convertedNumber = Int64.Parse(mergedNumber);
Int64 modulo = MathMod(convertedNumber, 97);
Int64 wynik = 98 - modulo;
string wynikString = string.Format("{0}", wynik.ToString().PadLeft(2, '0')); // must be 2 chars
indywidualnyNumerRachunku = wynikString + numerRozliczeniowyBanku + identyfikatorNumeruRachunku + indywidualnyNumerRachunku;
return indywidualnyNumerRachunku;
}
private static Int64 MathMod(Int64 a, Int64 b) {
return (Math.Abs(a * b) + a) % b;
}
}
The max value for Int64 is 9223372036854775807 (19 characters when printed). You will probably want to use BigInteger instead (which was introduced in .NET 4):
public static string generator(string pesel, string varKlientID) {
// I have cut some code here to keep it short
BigInteger convertedNumber;
if (BigInteger.TryParse(mergedNumber , out convertedNumber))
{
BigInteger modulo = convertedNumber % 97;
// The rest of the method goes here...
}
else
{
// string could not be parsed to BigInteger; handle gracefully
}
}
private static BigInteger MathMod(BigInteger a, BigInteger b)
{
return (BigInteger.Abs(a * b) + a) % b;
}
Int64.MaxValue is 9,223,372,036,854,775,807 that's 19 characters. So you just can't fit that in. I suggest looking at this question for working with big numbers.
Try this function instead of "MathMod":
static int ModString(string x, int y)
{
if (x.Length == 0)
return 0;
string x2 = x.Substring(0,x.Length - 1); // first digits
int x3 = int.Parse(x.Substring(x.Length - 1)); // last digit
return (ModString(x2, y) * 10 + x3) % y;
}
(since all of your numbers are positive, there is no point in using Math.Abs, as in your original MathMod function).
Use it this way:
modulo = ModString(mergedNumber,97);
This should works with all versions of .NET since 1.1, without the need of BigInteger.
The answer you are looking for is demonstrated here. It includes various manners to calculate the modulus for huge numbers. I used similar methods as described here for international bank account numbers.
A direct link to someone who has a copy pastable method is here.

Categories

Resources