Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# simple divide problem

Tags:

c#

I have this:

 double result = 60 / 23;

In my program, the result is 2, but correct is 2,608695652173913. Where is problem?

like image 900
Simon Avatar asked Nov 12 '10 08:11

Simon


People also ask

What C is used for?

C programming language is a machine-independent programming language that is mainly used to create many types of applications and operating systems such as Windows, and other complicated programs such as the Oracle database, Git, Python interpreter, and games and is considered a programming foundation in the process of ...

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.

Why is C named so?

Quote from wikipedia: "A successor to the programming language B, C was originally developed at Bell Labs by Dennis Ritchie between 1972 and 1973 to construct utilities running on Unix." The creators want that everyone "see" his language. So he named it "C".


1 Answers

60 and 23 are integer literals so you are doing integer division and then assigning to a double. The result of the integer division is 2.

Try

double result = 60.0 / 23.0;

Or equivalently

double result = 60d / 23d;

Where the d suffix informs the complier that you meant to write a double literal.

like image 57
James Gaunt Avatar answered Oct 11 '22 18:10

James Gaunt