To be more specific, I would like to know how to make it so that i can accept a two digit input from a user and perform addition on the two digits.
Example:
userInput = 42;
4+2 = 6.
I could not find out the name of this action so i could not find such an answer on here.
I should add that i would rather avoid creating more integers
Here is a method you can use. Just use a two character input string as a parameter. You'll either get an exception because the input string is invalid or the sum of both digits.
public int AddTwoDigitString(string input)
{
if(input == null)
throw new ArgumentNullException(nameof(input));
if(input.Length != 2)
throw new ArgumentException($"`{nameof(input)}` must be two characters long");
int firstDigit, secondDigit;
if(int.TryParse(input[0].ToString(), out firstDigit) == false)
throw new ArgumentException("First character is not an integer.");
if(int.TryParse(input[1].ToString(), out secondDigit) == false)
throw new ArgumentException("Second character is not an integer.");
return firstDigit + secondDigit;
}
You can do it by yourself by calculating:
int b= Int32.Parse(userinput);
int a =b%10+b/10;
and than if b its 42, so a will be 2+4=6
if you don't know how many digits you have:
int b= Int32.Parse(userinput);
int a=0;
while(b!=0)
{
a+=(b%10);
b=b/10;
}
You can try and use Aggregate function from System.Linq like this
return userInput.ToCharArray()
.Aggregate(0, (result, character) => result += int.Parse(character.ToString()));
where the lamda expresion is the accumulator function that will be executed for each character in the input.
You could try this:
int number;
{
Console.Write("Insert the number");
number = Convert.ToInt32(Console.ReadLine());
Console.Write("Equals" + Addition(number).ToString());
Console.ReadKey();
}
// Operation that returns the addition of the digits of a number
static int Addition(int number){
int acum = 0;
while (num != 0){
var digit = number % 10;
acum += digit;
number = number / 10;
}
return acum;
}
}
}
Related
I want a method to remove the comma from the decimal number and then collect the digits. For example, if the user inputs 1,3 it will remove the comma and collect 1 and 3 together. I mean 1+3 =4. Can I use trim or replace?
public int AddSum(string x1)
{
string x = x1.Trim();
int n = Convert.ToInt32(x);
return n;
}
public int AddSum(string x1)
{
var digitFilter = new Regex(#"[^\d]");
return digitFilter.Replace(x1, "").Select(c => int.Parse(c)).Sum();
}
OR
public int AddSum(string x1)
{
return x1.Where(c => char.IsDigit(c)).Select(c => c - '0').Sum();
}
If you want to iterate over the characters in a string and compute the sum of digits contained therein, it's trivial:
public static int SumOfDigits( string s ) {
int n = 0;
foreach ( char c in s ) {
n += c >= '0' && c <= '9' // if the character is a decimal digit
? c - '0' // - convert to its numeric value
: 0 // - otherwise, default to zero
; // and add that to 'n'
}
return n;
}
It sounds like you want take a comma-separated string of numbers, add the numbers together, then return the result.
The first thing you have to do is use the Split() method on the input string. The Split() method takes an input string splits the string into an array of strings based on a character:
string[] numbers = x1.Split(',');
So now we have an array of strings called numbers that hold each number. The next thing you have to do is create an empty variable to hold the running total:
int total = 0;
The next thing is to create a loop that will iterate through the numbers array and each time, add the number to the running total. Remember that numbers is an array of strings and not numbers. so we must use the Parse() method of int to convert the string to a number:
foreach (string number in numbers)
{
total += int.Parse(number);
}
Finally, just return the result:
return total;
Put it all together and you got this:
private static int AddSum(string x1)
{
string[] numbers = x1.Split(',');
int total = 0;
foreach (string number in numbers)
{
total += int.Parse(number);
}
return total;
}
I hope this helps and clarifies things. Keep in mind that this method doesn't do any kind of error checking, so if your input is bad, you'll get an exception probably.
So my code is to check if a given number is a 'happy number'. It squares each digit of the number, adds them and continues to do so until either the result of the addition is 1 (which means it is a happy number) or until it results in a 4 (which means it is not a happy number).
What's happening is that there are many numbers which cause an infinite loop (therefore meaning they are not a happy number) and I'm wondering how I would construct my code so that it will detect when there's an infinite loop occuring? I have some ideas but all flawed.
My code is as follows:
using System;
namespace Happy_numbers_problem
{
class Program
{
static int HappyNumbers(string Number)
{
string Output = Number;
while ((Convert.ToInt32(Output) != 1) && (Convert.ToInt32(Output) != 4))
{
string Result2 = "0";
for (int Index = 0; Index < Output.Length; Index++)
{
string Character = Output.Substring(Index, 1);
int Calc = Convert.ToInt32(Character);
int Result = Calc * Calc;
//Adding Result2 and Result, then turning it into a string.
Result2 = Convert.ToString(Convert.ToInt32(Result2) + Result);
if (Index == (Output.Length) - 1)
{
Output = Result2;
}
}
}
return Convert.ToInt32(Output);
}
static void Main(string[] args)
{
Console.WriteLine("Please enter a number");
string Number = Console.ReadLine();
int Output = HappyNumbers(Number);
if (Output == 1)
{
Console.WriteLine(Number + " is a happy number");
}
else if (Output == 4)
{
Console.WriteLine(Number + " is not a happy number");
}
else
{
Console.WriteLine(Number + " is not a happy number");
}
}
}
}
The problem resides in your while condition. If your output needs to be 1 or 4 to break out of the loop and deliver the output to latter be analysed, you have to use the operator or || instead of the operator and &&.
I'm trying to calculate the number of digit before the floating points. for example
input: 123.4
expected output: 3
my actual output: 5
I'm sure there is something wrong with the digit.equals(".") since the program does not break out of the loop.
this is my code:
public class Program
{
public static void Main()
{
Console.WriteLine(HowManyDigit(123.4));
}
public static Int32 HowManyDigit(Double number)
{
string x = number.ToString();
var counter = 0;
for (int i = 0; i < x.Length; i++)
{
var digit = x[i];
//Console.WriteLine(counter);
if (digit.Equals("."))
{
break;
}
else
{
counter++;
}
}
return counter;
}
}
The reason your code does not work breaks down to this logic:
var digit = x[i];
if (digit.Equals("."))
{
break;
}
The char digit will never be equal to the string "."
If you change your code to:
//Note that I use a char, indicated by ''
if (x[i].Equals('.'))
{
break;
}
Or simply:
if (x[i] == '.')
{
break;
}
Either of those two methods will give you a drastically different result from your current code.
That being said, this method is not really the best way of doing what you want. You can simply use IndexOf() to get the exact number you want:
public static int HowManyDigit(double number)
{
return number.ToString().IndexOf('.');
}
Fiddle here
Just compute the logarithm of base 10 and then convert to integer with floor.
n = Math.Floor(Math.Log10(x))+1;
Try this x.IndexOf('.') this will be your answer
Replace this:
if (digit.Equals("."))
With this:
if (digit.Equals('.'))
Now your output should be 3.
Here is a LINQ solution:
double number = 123.4;
var result = number.ToString().TakeWhile(x => char.IsDigit(x)).Count();
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());
}
}
Is there a way to format a double number that always have n digits sepecified by user?
For example if user want to see always 4 digits, take the following numbers as example:
Original Formatted
------- ---------
3.42421 3.424
265.6250 265.6
812.50 812.5
12.68798 12.68
0.68787 0.687
I made up this but it just allows for number of floating points! it is not what I wanted!
public string ToEngV(double d, int percision = 0)
{
string zeros = string.Empty;
if (percision <= 0)
{
zeros += "0";
}
else if (percision > 0)
{
for (int i = 0; i < percision; i++)
{
zeros += "0";
}
}
return String.Format("{0:0." + zeros + "}", d)
}
Imagine I call the above method for a number like 812.50 and I set the precision to (this is now used for all numbers I am going to format). Obviously the output will be 812.5
But if I give the another number like 1.61826 I will get 1.6 and this ruins the formatting in the page I show these number to users. I need that to be 1.618
Thus I want my method to always show N digit!
I'm not sure if your asking to round or truncate numbers, so I wrote this method:
public static string ToEngV(this double d, int digits, bool round)
{
var lenght = Math.Truncate(d).ToString().Length;
if (lenght > digits)
{
throw new ArgumentException("...");
}
int decimals = digits - lenght;
if (round)
{
return Math.Round(d, decimals).ToString();
}
else
{
int pow = (int)Math.Pow(10, decimals);
return (Math.Truncate(d * pow) / pow).ToString();
}
}
Example:
var numbers = new double[] { 3.42421, 265.6250, 812.50, 12.68798, 0.68787 };
foreach (var number in numbers)
{
Console.WriteLine(number.ToEngV(4, false));
}
Console.WriteLine()
foreach (var number in numbers)
{
Console.WriteLine(number.ToEngV(4, true));
}
Output:
3.424
265.6
812.5
12.68
0.687
3.424
265.6
812.5
12.69
0.688
Note that if your number has more integer digits than digits you will get an ArgumentException.
number.ToString("#0.000").Substring(0, 5);
I'm not sure this is what you're searching for, anyway give it a try:
string FmtDbl(double num, int digits)
{
digits++; // To include decimal separator
string ret = num.ToString();
if (ret.Length > digits) return ret.Substring(0, digits);
else return ret + new String('0', digits - ret.Length);
}
Note that if your number has more than digits integer digits, this doesn't work...
What about something like:
d.ToString().PadRigth(4,'0').SubString(0,4);
public static void RunSnippet()
{
Console.WriteLine(myCustomFormatter(3.42421));
Console.WriteLine(myCustomFormatter(265.6250));
Console.WriteLine(myCustomFormatter(812.50));
Console.WriteLine(myCustomFormatter(12.68798));
Console.WriteLine(myCustomFormatter(0.68787));
Console.ReadLine();
}
public static double myCustomFormatter(double value)
{
string sValue = value.ToString();
string sFormattedValue = sValue.Substring(0,5);
double dFormattedValue= Convert.ToDouble(sFormattedValue);
return dFormattedValue;
}