Binary to Decimal Conversion doesn't work - c#

This is kind of a funky program. For some reason it works when the binary input is something like 101. Then it doesn't for 1000. This is kind of odd. Could someone please explain?
class Program
{
static void Main()
{
string binary = "xxx";
double decimalValue = 0;
Console.WriteLine("Enter in a binary number:");
binary = Console.ReadLine();
for (int i = 0; i < binary.Length; i++)
{
Console.WriteLine("Length is: {0}", binary.Length);
if (binary[i] == 49) //Look at that
decimalValue = decimalValue + Math.Pow(2, i);
}
Console.WriteLine("The decimal equivalent value is {0}", decimalValue);
Console.ReadLine();
}
}
The heart of it is of course
if (binary[i] == 49)
I'm just making it to teach myself some C#. Could someone tell me what to put on the right side other than 49, which is the ASCII number for "1". If I put "1" I get an error saying you can't compare a string to a char.
Any help would be appreciated. I don't want to use the pre-canned convert to binary method, because this is supposed to be a teachable moment.

You read the characters from the wrong end.
As was said immediately in the first comment to the question, by Lucas Trzesniewski, replace one use of i (not both) inside the for loop with binary.Length - 1 - i.
The reason why it works for "101" is that this is a palindrome (reads the same backwards).
Note: 49 is the ASCII code for '1'. It is more readable to use == '1' than == 49. However, both work equally well. In C# you get a char value if you use single quotes, as in '1', and you get a string object reference if you use double quotes, "1".
You should remove the stuff with "xxx". It has no function. Just dostring binary = Console.ReadLine();.

Instead of trying to add the value of each individual bit based on it's position you could take another approach: shift and add. In this approach you shift the current value to the left (by multiplying that value by 2) and adding the current bit.
For instance: the binary value 1010 becomes decimal 10 in four cycles:
value = 0
value *= 2 => value = 0
value += bit 1 => value = 1
value *= 2 => value = 2
value += bit 0 => value = 2
value *= 2 => value = 4
value += bit 1 => value = 5
value *= 2 => value = 10
value += bit 0 => value = 10
Or, in code:
using System;
public class Program
{
public static void Main()
{
string binary = "";
double decimalValue = 0;
Console.WriteLine("Enter in a binary number:");
binary = Console.ReadLine();
for (int i = 0; i < binary.Length; i++)
{
decimalValue *=2; // shift current value to the left
if (binary[i] == 49)
{
decimalValue += 1; // add current bit
}
Console.WriteLine("Current value: {0}", decimalValue);
}
Console.WriteLine("The decimal equivalent value is {0}", decimalValue);
Console.ReadLine();
}
}

Related

Subtraction between multiple random input numbers

i want to make user input random number example : 5-3-10-50
, system will split " - " and then the result 5 3 10 50
, how to make subtraction from first number minus second number and so on,
like this 5 - 3 = 2 , 2 - 10 = -8 , -8 - 50 = -58
and then system will print the final answer -58
my code :
bool Subtraction = true;
int AskSubtraction = 0;
while (Subtraction)
{
Console.Write("\n" + "input number ( example : 1 - 2 - 3 - 4 ) : ");
var InputNumber = Console.ReadLine();
double Answer = 0;
foreach (var result in InputNumber.Split('-'))
{
if (double.TryParse(result, out _))
{
double NumberResult = Convert.ToDouble(result);
Answer -= NumberResult;
}
else
{
Console.WriteLine("\n" + "Wrong input !");
AskSubtraction++;
}
}
Console.WriteLine("\n" + "subtraction result : " + Answer);
}
i know my code is wrong, im beginner i already try to fix this but i cant fix it until now, i hope someone tell me what's wrong with my code and fix it too, thank you.
The reason yours doesn't work is because you set Answer = 0.
And you used foreach. On the first iteration of the loop, the first number is subtracted from Answer which results in -5.
Use for (int i=1; i<arr.Length; i++)
instead of foreach
Start from index 1, and then subtract the values.
Example:
var arr = InputNumber.Split('-');
double Answer = 0;
if (double.TryParse(arr[0], out _))
{
// We set Answer to the first number, since nothing is subtracted yet
Answer = Convert.ToDouble(arr[0]);
}
// We start index from 1, since subtraction starts from 2nd number on the String array
for (int i=1; i<arr.Length; i++)
{
if (double.TryParse(arr[i], out _))
{
double NumberResult = Convert.ToDouble(arr[i]);
Answer -= NumberResult;
}
}
Tested on Online C# Compiler
You would need a condition inside the foreach loop to check for the first parsed double before you begin subtraction. Also there is no need to call Convert.ToDouble() since the double.TryParse() function already returns the parsed double value, All you would need is a variable to contain the out value of the double.TryParse() function, See example below
bool Subtraction = true;
int AskSubtraction = 0;
while (Subtraction)
{
Console.Write("\n" + "input number ( example : 1 - 2 - 3 - 4 ) : ");
var InputNumber = Console.ReadLine();
double Answer = 0;
double numResult;
foreach (var result in InputNumber.Split('-'))
{
if (double.TryParse(result, out numResult))
{
if(Math.Abs(Answer)>0){
Answer -= numResult;
}
else{
Answer=numResult;
}
}
else
{
Console.WriteLine("\n" + "Wrong input !");
AskSubtraction++;
}
}
Console.WriteLine("\n" + "subtraction result : " + Answer);
}

Getting the sum of all numbers in a character array

I have converted string to char[], but now when I try to get a total of all the numbers in the array, I get a wrong output. The goal is that if the user enters a number as a string e.g - 12, the output should be 3 i.e 1 + 2, another example - 123 should be 1+2+3 = 6.
I am new to coding. My apologies for any inconvienence.
static void Main(string[] args)
{
int sum = 0;
String num = Console.ReadLine();
char[] sep = num.ToCharArray();
for (int i = 0; i < sep.Length; i++)
{
sum += (sep[i]);
}
Console.WriteLine(sum);
Console.ReadLine();
}
You are currently adding ascii values. The ascii value of 1 is 49 and that of 2 Is 50... You need to use int.TryParse to convert from char to int.
int value;
for (int i = 0; i < sep.Length; i++)
{
if (int.TryParse (sep[i].ToString(),out value))
sum += value;
}
If you want to calculate sum of digits, you need to convert each char to int first. Char needs to be converted to string and then parsed into int. Your original code contains implicit conversion, which converts 1 and 2 into 49 and 50 (ASCII), thus the sum ends up being 99.
Try this code instead:
static void Main(string[] args)
{
int sum = 0;
String num = Console.ReadLine();
char[] sep = num.ToCharArray();
for (int i = 0; i < sep.Length; i++)
{
sum += int.Parse(sep[i].ToString());
}
Console.WriteLine(sum);
Console.ReadLine();
}
Just for fun here is a LINQ solution.
var sum = num.Select( c => int.Parse((string)c) ).Sum();
This solution takes advantage of the fact that a string is also an IEnumerable<char> and therefore can be treated as a list of characters.
The Select statement iterates over the characters and converts each one to an integer by supplying a lambda expression (that's the => stuff) that maps each character onto its integer equivalent. The symbol is typically prounced "goes to". You might pronounce the whole expression "C goes to whatever integer can be parsed from it."
Then we call Sum() to convert the resulting list of integers into a numeric sum.

Multiplying Different Data Types in an Array in C#

I am receiving an error "Operator '*' cannot be applied to operands of type 'int' and 'decimal[]'", as I am attempting to multiply two values with different data types (one being a value located in an array). My question is how am I able to multiple numberOfMinutes * perMinuteRate in my code below? My variable is called total, which I declared a double data type (although may be incorrect).
I tried changing data types and played with formatting (like ToString), but I am not sure what to do. I also tried to google the answer with no success.
I am by no means a professional programmer; I'm not in school. I'm a data analyst who is learning to program.
Here is my code:
static void Main(string[] args)
{
int[] areaCodes = { 262, 414, 608, 715, 815, 920 };
decimal[] perMinuteRate = { .07m, .1m, .05m, .16m, .24m, .14m };
int numberOfMinutes;
int userAreaCode;
string inputString = "1";
while (inputString != "0")
{
int x;
Console.WriteLine("Enter the area code for your call (or 1 to end):");
inputString = Console.ReadLine();
userAreaCode = Convert.ToInt32(inputString);
Console.WriteLine("How many minutes will your call last?");
inputString = Console.ReadLine();
numberOfMinutes = Convert.ToInt32(inputString);
for (x = 0; x < areaCodes.Length; x++)
{
if (userAreaCode == areaCodes[x])
{
***double total = numberOfMinutes * perMinuteRate;***
Console.WriteLine("You call to {0} will cost {1} per minute for a total of {2}.", areaCodes[x], perMinuteRate[x].ToString("C"), total.ToString("C"));
x = areaCodes.Length;
}
}
if (x != areaCodes.Length)
{
Console.WriteLine("I'm sorry; we don't cover that area.");
inputString = "1";
}
else
{
Console.WriteLine("Thanks for being our customer.");
inputString = "0";
}
Console.ReadLine();
}
}
Thank you in advance.
Change:
double total = numberOfMinutes * perMinuteRate;
to
double total = (double)(numberOfMinutes * perMinuteRate[x]);
The same way you index into perMinuteRate in the line directly below.
The expression [int] * [decimal] will result in a decimal, and the cast (double) will convert it to a double
To avoid loss of precision, change it to:
decimal total = numberOfMinutes * perMinuteRate[x];

Finding out whether a number is a palindrome or not in C#

I am new to C# and was doing this program as an exercise. I have managed to get my program to print the reversed number of the input given by the user, but when I move onto checking whether it is a palindrome or not, it does not calculate the answer correctly. It always prints 'not a palindrome'.
After some error checking, I realized that the reason why it was doing this is because the last number that gets stored in newnum is just the last digit after being reversed and not the entire number. How can I rectify this??
My Code
int i, remainder = 0, newnum = 0;
Console.WriteLine("Enter a Number: ");
int uinput = Convert.ToInt32((Console.ReadLine()));
for (i = uinput; i > 0; i = (i / 10))
{
remainder = i % 10;
Console.Write(remainder);
newnum = remainder;
}
if (newnum == uinput)
{
Console.WriteLine("The Number {0} is a palindrome", uinput);
}
else
{
Console.WriteLine("Number is not a palidrome");
}
Console.WriteLine(uinput);
Console.WriteLine(newnum);
Console.ReadKey();
}
I also looked online at another code example, but the thing I don't understand in that is why num is being converted to boolean type in the while loop? Is that just to keep the loop running?
The Code reffered to above
int num, rem, sum = 0, temp;
//clrscr();
Console.WriteLine("\n >>>> To Find a Number is Palindrome or not <<<< ");
Console.Write("\n Enter a number: ");
num = Convert.ToInt32(Console.ReadLine());
temp = num;
while (Convert.ToBoolean(num))
{
rem = num % 10; //for getting remainder by dividing with 10
num = num / 10; //for getting quotient by dividing with 10
sum = sum * 10 + rem; /*multiplying the sum with 10 and adding
remainder*/
}
Console.WriteLine("\n The Reversed Number is: {0} \n", sum);
if (temp == sum) //checking whether the reversed number is equal to entered number
{
Console.WriteLine("\n Number is Palindrome \n\n");
}
else
{
Console.WriteLine("\n Number is not a palindrome \n\n");
}
Console.ReadLine();
Any sort of help is much appreciated!! Thank You :)
I'm not sure what you're asking, since the second snippet of code you found online should fix your issue.
Your code works, if you just change the line
newnum = remainder;
to
newnum = (newnum*10) + remainder;
The issue in your case is not the condition you used in the for loop, it's just that you're overwriting newnum with the remainder every time, so newnum is only storing the last reminder that was calculated in the loop, "forgetting" all the others it had calculated before.
To reverse the number, every time you enter the loop, you should add the last remainder you've found to the right of newnum, which is effectively equivalent to multiplying everything by 10 and adding remainder.
Try to follow it step by step with pen and paper (or with a debugger).
public bool isPalindome(int num)
{
string sNum = num.ToString();
for (int i = 0; i<sNum.Length; i++)
if (sNum[i] != sNum[sNum.Length-1-i]) return false;
return true;
}
I think that will do it... Untested!!
As dognose (and Eren) correctly assert you only need to go halfway through
public bool isPalindome(int num)
{
string sNum = num.ToString();
for (int i = 0; i < sNum.Length/2; i++)
if (sNum[i] != sNum[sNum.Length-1-i]) return false;
return true;
}
You will also need to decide what happend to negative numbers.. ie is -121 a plaindome? This method will say that it isn't...
Easiest way:
public static Boolean isPalindrom(Int32 number){
char[] n1 = number.ToString().ToCharArray();
char[] n2 = number.ToString().ToCharArray();
Array.Reverse(n2);
String s1 = new String(n1);
String s2 = new String(n2);
return (s1 == s2);
}
https://dotnetfiddle.net/HQduT5
you could also use Integers for s1 and s2 and return (s1-s2 == 0)
You have many ways of accomplish this exercise.
A. You can leave the input as string and loop it over, every iteration to check if the value of index 'i' and value of index 'len-i-1' are equals, if not false, otherwise return at the end of the loop true. (the loop should run till i < len/2)
B. You can create a new string and insert the text from end to start and then compare if the original string and result string are equals.
C. there are much more ways without using the string solutions, just with calculation..
int x;
cin<<x; //input the number
int ar[];
int i=0;
temp2=0;
while(x/10 != 0)
{
int temp=x%10;
ar[i]=temp;
x=x/10;
i++;
}
for(int j=0, j<i,j++)
{
temp2=temp2*10+ar[j];
}
if(temp2==x){cout<<"palindrome"}
else {"not palindrome"}
ok here is the logic:
we first input the number x(it can be of any length)..Next we split the number into array..the condition to do this is tha we check for the qoutient to decide whether the number is fully split..next we take the array and rejoin it and check with the input number..
Use the following code:
public boolean isPalindrom(Integer number)
{
return number.Equals(int.Parse(String.Join("", String.Join("", number.ToString().ToCharArray().Reverse().ToArray()))));
}

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()

Categories

Resources