-5

Hello guys I am trying to divide 4 by 3 using c#.

I have tried the following so far and in each case the answer is 1

float a = 4/3;// returns a = 1

I have tried this with Decimal and still the result is the same. I am not a C programmer is there any way I can get a engineering result like 1.333

Flood Gravemind
  • 3,773
  • 12
  • 47
  • 79

5 Answers5

2

You need to use the 'f' suffix to tell the compiler the literal is a float

float a = 4f / 3f;

Otherwise it will assume an integral and you will get an integral result.

Weyland Yutani
  • 4,682
  • 1
  • 22
  • 28
  • Not it won't, it's specifically declared as a float. If he'd use `var`, then he should use the suffix. Edit: Oh ofcourse, nevermind. My mind was elsewhere. – Jeroen Vannevel Oct 24 '13 at 14:49
  • it doesn't matter that a is declared as a float. 4 and 3 are literals. The compiler will assume they are integrals. 4/3 will produce 1 and a will be set to 1.0 – Weyland Yutani Oct 24 '13 at 14:50
  • @JeroenVannevel, No, having `a` declared as `float` wouldn't have any effect so `float a = 4 / 3` would return `1` – Habib Oct 24 '13 at 14:51
  • @WeylandYutani In the context of the original question this is a poor answer; in the context of the edited question it's not bad. That's because this answer entirely ignored the first case, instead only discussing the second. – Servy Oct 24 '13 at 14:51
  • 1
    The original question was wrong. The first case was incorrect as I pointed out in the comments. So I ignored it. – Weyland Yutani Oct 24 '13 at 14:55
2

Case 1 gives me 1.333. Case 2 is actually integer division, because 4 and 3 are integers, defined in line.

float a = 4f / 3; will work as the RHS is then evaluated to floating point.

Will Faithfull
  • 1,868
  • 13
  • 20
2

.NET have 3 types of division. From 7.7.2 Division operator

  • Integer division
  • Floating-point division
  • Decimal division

With float a = 4 / 3; actually you are doing integer division and assign it in a float variable. As written in documentation;

The division rounds the result towards zero, and the absolute value of the result is the largest possible integer that is less than the absolute value of the quotient of the two operands.

If you want to do floating-point division, you can do one of these;

float a = 4f / 3f;
float a = 4 / 3f;
float a = 4f / 3;
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
1

As both numbers are integers you are using the integer division

try with one or both float numbers

float a = 4 / 3f;
Esteban Elverdin
  • 3,552
  • 1
  • 17
  • 21
0

Try replacing the values a and b with 4.0 and 3.0 respectively

Conway Stern
  • 152
  • 2
  • 10