Simple math program.

  • Thread starter Thread starter Eric Anderson
  • Start date Start date
E

Eric Anderson

Would someone be kind and explain why and how this works. It comes up with the correct answer, but I dont understand how it does. Wouldn't Console.WriteLine("5+4={0}",5+4); wouldn't it come up as 5+4=1 instead of 5+4=9? Sorry guys im new to all of this but im learning. Thanks for the help in advance!
using System;

namespace SimpleMath

{



class DoMath

{

static void Main(string[] args)

{

int a = 1;


//addition with integers works as expected


Console.WriteLine("5 + 4 = {0}", 5 + 4);


Console.Write("Please press \"enter\" to continue");

Console.ReadLine();

} // end main

} // end class

} // end namespace
 
Eric said:
Would someone be kind and explain why and how this works. It comes up with the
correct answer, but I dont understand how it does. Wouldn't
Console.WriteLine("5+4={0}",5+4); wouldn't it come up as 5+4=1 instead of 5+4=9?
Sorry guys im new to all of this but im learning. Thanks for the help in advance!

Why would it come up as 5+4=1?
If you wrote: Console.WriteLine ("5+4={0}", a); that would come up as
5+4=1, but you're passing it the right answer, so I don't see why you'd
expect it to print the wrong one...

Jon
 
The {0} is substituted for the appropriate argument (in this case 5+4).
The argument evaluates to 9 and is inserted into the string as position
{0}. Why did you expect it to be 1? Not having a go, just interested.

Simon

As a further example

Console.WriteLine("5 + 4 = {0} and 5 - 4 = {1}", 5+4, 5-4);

would result in

5 + 4 = 9 and 5 - 4 = 1
 
Lol I know that 5+4 equals to. The reason why I asked is just to understand what was going on in that line of code, because the book that I am reading didn't clarify what all that meant. And I just want to get a full understanding of everything before I move on to the next part. But thanks guys for clearing that up for me.

--
(\(\
(=':')
(,(")(") Eric Anderson
Would someone be kind and explain why and how this works. It comes up with the correct answer, but I dont understand how it does. Wouldn't Console.WriteLine("5+4={0}",5+4); wouldn't it come up as 5+4=1 instead of 5+4=9? Sorry guys im new to all of this but im learning. Thanks for the help in advance!
using System;

namespace SimpleMath

{



class DoMath

{

static void Main(string[] args)

{

int a = 1;


//addition with integers works as expected


Console.WriteLine("5 + 4 = {0}", 5 + 4);


Console.Write("Please press \"enter\" to continue");

Console.ReadLine();

} // end main

} // end class

} // end namespace
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top