How to fix the following code showing this error - c#

The following code below is concatenating the double variable .
For example first number is 2
And second is 3
It is adding them like this 2+3;
23
using System;
public static class Program
{
public static void Main()
{
double num01;
double num02;
Console.WriteLine("Add");
Console.Write("type a number: ");
num01 = Convert.ToInt32(Console.ReadLine());
Console.Write("type another number: ");
num02 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("the result is " + num01 + num02);
Console.ReadKey();
}
}

You have not added 2 integers together, you have suffixed a string with 2 other numbers.
String concatenation is also 'slow'. You should use string.Format or string interpolation.
Console.WriteLine(string.Format("the result is {0}", num01 + num02) );
or
Console.WriteLine($"the result is {num01 + num02}");

The reson is that expression "the result is " + num01 + num02 is adding, which includes string, which makes the whole operation concatentaion, not addition of numbers! If at least one operand of + operator is string, it makes it concatenation.
Moreover, then every other operand is converted to string, so your numbers get converted to string and then concatenated.
To prevent that, force order of operation, so addition of your numbers is first, for example (already shown in other answers): "the result is " + (num01 + num02)
Now it will first sum two numbers, then concatenate with given string.

If you add the parentheses to the sum of the number, your code can work
double num01;
double num02;
Console.WriteLine("Add");
Console.Write("type a number: ");
num01 = Convert.ToInt32(Console.ReadLine());
Console.Write("type another number: ");
num02 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("the result is " + (num01 + num02));
Console.ReadKey();
but the best practice without a doubt is:
string.Format

"It is adding them like this 2+3; 23 "
That is because you are using + in a context where it treats 2 and 3 as strings and with strings + always perform concatenation, hence the result 23
What do you need to do to fix things?
Console.WriteLine("the result is " + (num01 + num02) );
Why does the above solution works?
Short answer: Operator precedence. Parenthesis has higher precedence and is evaluated first. When that happens num01 and num02 are treated as numbers and addition takes place. And now this sum value is treated like a string in + with "the result is "

What's going on: for
"the result is " + num01 + num02
we have
"the result is " + num01 which is "the result is 1" (adding double to string)
"the result is 1" + num02 which is "the result is 12" (adding double to string)
what can you do: put (..) and have "the result is " + (num01 + num02):
num01 + num0 which is 3 (adding two doubles)
"the result is " + 3 which is "the result is 3" (adding double to string)
So you can either put (...)
Console.WriteLine("the result is " + (num01 + num02));
or (better way) use string interpolation and let .net compute the sum for you:
Console.WriteLine($"the result is {num01 + num02}");
or formatting:
Console.WriteLine("the result is {0}", num01 + num02);

Related

Why are my results not being written to the Console like I expect them to?

I'm writing a program that lets you input two numbers and gives you all the math answers for it. So like multiplication, division, etc. Problem is when I run it, it asks for the input and then it just shows all the operator strings but empty and then ends there.
I tried making an array and then setting that equal to the operators in the Console.WriteLines but that didn't work.
static void Main(string[] args)
{
Console.WriteLine("Input any two numbers.");
var number1 = int.Parse(Console.ReadLine());
var number2 = int.Parse(Console.ReadLine());
Console.WriteLine("Addition: ", + (number1 + number2));
Console.WriteLine("Division: ", + (number1 / number2));
Console.WriteLine("Subtraction: ", + (number1 - number2));
Console.WriteLine("Multiplication: ", + (number1 * number2));
}
You wrote:
Console.WriteLine("Addition: ", + (number1 + number2));
You meant to write
Console.WriteLine("Addition: " + (number1 + number2));
Note that you added an extra comma.
This code is legal, but bad style. See below for better ways to write this.
What is the meaning of the code you wrote? Console.WriteLine lets you do this:
Console.WriteLine("Addition:{0} + {1} = {2}", number1, number2, number1 + number2);
That is "replace {0} with the first thing following, {1} with the second thing, and so on".
So the code you wrote was "replace {0} with the value of +(number1+number2), but you don't have a {0}, so, nothing happens.
Today would be a great day for you to learn about interpolated strings:
Console.WriteLine($"{number1} + {number2} = {number1 + number2}");
Notice the $ that indicates that the string is interpolated; expressions inside {} will be evaluated and turned into text.
Concatenation with string returns string but you have to write it like that: Console.WriteLine("Division: "+(number1 / number2));
You can also use placeholder Console.WriteLine("Division: {0}",(number1 / number2));
or string interpolation Console.WriteLine($"Division: {number1 / number2}");

How does c# string evaluates its own value?

Why does this snippet of code
string str = 30 + 20 + 10 + "ddd";
Console.WriteLine(str);
produces 60ddd,
and this one
string str = "ddd" + 30 + 20 + 10;
Console.WriteLine(str);
produces ddd302010?
Seems like it's very simple, but I can't get my head around it.
Please, show me direction in which I can go in order to find a detailed answer.
Thanks!
The + operators in the expression you show have equal precedence because they're the same operator, hence are evaluated left to right:
30 + 20 + 10 + "ddd"
-- + (int, int) returns (int)50
------- + (int, int) returns (int)60
------------ + (object, string) returns (string)"60ddd"
Then for the other case:
"ddd" + 30 + 20 + 10
----- + (string, object) returns (string)"ddd30"
---------- + (string, object) returns (string)"ddd3020"
--------------- + (string, object) returns (string)"ddd302010"
It's because an expression is evaluated from left side to right side. In the first example 30 + 20 + 10 gives you int + string (30 + 20 + 10) - int, "ddd" - string. In the second example "ddd" + 30 is a string "ddd30" that appends "20" and "10" to it. It's all about the order (unless you have paranthesis).
It's evaluated from left to right. The first example has the numbers first, so it starts by evaluating as numbers. Then it finds out it has to evaluate as string. The second example is the other way around. It starts with string and continues with string.
Operator + has different overloads:
int + int = int
int + string = string
string + int = string
In Following Expression:
string str = 30 + 20 + 10 + "ddd";
Console.WriteLine(str);
First 30 + 20 got evaluates both are integers so output of operator will be integer which is 50.
Then 50 + 10 will be evaluated which both are again integers so integer will be output which is 60.
Then 60 + "ddd" which is integer + string operation the operator in this case output string so 60 + "ddd" will output 60ddd.
In Following Expression:
string str = "ddd" + 30 + 20 + 10;
Console.WriteLine(str);
First "ddd" + 30 got evaluates in which string + integer operation takes place so output will be ddd30.
Then ddd30 + 20 will get evaluated in which again string + integer operation takes place so output will be ddd3020.
Then ddd3020 + 10 will get evaluated in which again string + integer operation takes place so output will be ddd302010.
It happens because, the order of operations if from left to right. But assigment is last operation.
To assing value first expression must be calculated.

Peso Symbol in C#

if (num1 == 5)
{
Console.WriteLine("\nThe " + num2 + " kilo/s of {0} " + 28 + " per kilo ", "GRAPES");
Console.WriteLine("The total amount is {0}{1}", num2.ToString("en-PHI"),num2*28);
}
num2.ToString("en-PHI")
I try this one but it doesn't work at all .. it just copy the en-PHI..
Sounds like you want to provide the culture en-PHI... although that isn't a valid culture name apparently. Perhaps you just want phi as the language?
var culture = CultureInfo.GetCultureInfo("phi");
var text = string.Format(culture, "The total amount is {0:c}", num2 * 28);
Console.WriteLine(text);
The c format specifier is "currency".
That's the way of printing the currency symbol known for a specific culture... now that might not do exactly what you want, but it's probably a matter of finding the right culture.
If you really just want to hard-code the peso character (U+20B1) you can do that directly:
Console.WriteLine("The total amount is \u20b1{0}", num2);
Now if that prints a "?" it means the current console encoding or font doesn't support the peso symbol. Running this from the command line will set it to UTF-8:
> chcp 65001
Make sure the font you're using supports the character as well.

Console.Writeline -- Why output is missing

Absolute newbie to C#. Was trying to run this program and the output simply would not show any computations.Why? I did not want to go through p,q,r,s for add, sub, multiply, divide etc., Also, how can i put space between "Please enter a number" and userName?
string userName;
double x, y;
Console.WriteLine(" Enter Your Name ");
userName = Console.ReadLine();
Console.WriteLine(" Please Enter A Number "+ userName);
First = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Please Enter Another Number"+ userName);
Second = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("The addition of Two Numbers is",x,y, x*y);
Console.WriteLine("The substraction of Two Numbers is",x,y,x/y);
Console.WriteLine("The multiplication of Two Numbers is",x,y,x * y);
Console.WriteLine("The division of Two Numbers given is", x,y,x / y);
Console.ReadKey();
When you pass additional parameters to show output, you must tell WriteLine where to put it by adding placeholders to the format line, like this:
Console.WriteLine("The product of Two Numbers {0} and {1} is {2}", x, y, x*y);
Positions are zero-based. The printed value of the first additional parameter (i.e. x) will replace {0}; the value of y will replace {1}, and the value of x*y will replace {2} in the final output.
The reason you did not have to do it with userName is that you passed a single parameter:
Console.WriteLine("Please Enter Another Number " + userName);
The result of appending userName to "Please Enter Another Number" string is passed as a single parameter to WriteLine. You could rewrite it with a format specifier, like this:
Console.WriteLine("Please Enter Another Number {0}", userName);
Totally agree with dasblinkenlight. Additionally, you may meet this line of code
Console.WriteLine("{0}, {1}", "Hello", 53);
Result in this line being written: Hello, 53. {0} is the placeholder for the first argument after the format string, {1} is the second, and so on. This is called composite formatting in .NET - http://msdn.microsoft.com/en-us/library/txafckwd%28v=vs.110%29.aspx

Format decimal value to string with leading spaces

How do I format a decimal value to a string with a single digit after the comma/dot and leading spaces for values less than 100?
For example, a decimal value of 12.3456 should be output as " 12.3" with single leading space. 10.011 would be " 10.0". 123.123 is "123.1"
I'm looking for a solution, that works with standard/custom string formatting, i.e.
decimal value = 12.345456;
Console.Write("{0:magic}", value); // 'magic' would be a fancy pattern.
This pattern {0,5:###.0} should work:
string.Format("{0,5:###.0}", 12.3456) //Output " 12.3"
string.Format("{0,5:###.0}", 10.011) //Output " 10.0"
string.Format("{0,5:###.0}", 123.123) //Output "123.1"
string.Format("{0,5:###.0}", 1.123) //Output " 1.1"
string.Format("{0,5:###.0}", 1234.123)//Output "1234.1"
Another one with string interpolation (C# 6+):
double x = 123.456;
$"{x,15:N4}"// left pad with spaces to 15 total, numeric with fixed 4 decimals
Expression returns: " 123.4560"
value.ToString("N1");
Change the number for more decimal places.
EDIT: Missed the padding bit
value.ToString("N1").PadLeft(1);
Many good answers, but this is what I use the most (c# 6+):
Debug.WriteLine($"{height,6:##0.00}");
//if height is 1.23 => " 1.23"
//if height is 0.23 => " 0.23"
//if height is 123.23 => "123.23"
All above solution will do rounding of decimal, just in case somebody is searching for solution without rounding
decimal dValue = Math.Truncate(1.199999 * 100) / 100;
dValue .ToString("0.00");//output 1.99
Note the "." could be a "," depending on Region settings, when using string.Format.
string.Format("{0,5:###.0}", 0.9) // Output " .9"
string.Format("{0,5:##0.0}", 0.9) // Output " 0.9"
I ended up using this:
string String_SetRPM = $"{Values_SetRPM,5:##0}";
// Prints for example " 0", " 3000", and "24000"
string String_Amps = $"{(Values_Amps * 0.1),5:##0.0}";
// Print for example " 2.3"
Thanks a lot!

Categories

Resources