0

This code gives me the correct volume of a sphere:

public static double CalculateBallVolume(double aRadius)
{
    double volume = (4.0 / 3.0) * Math.PI * Math.Pow(aRadius,3);

    return volume;
}

but if I write it like this, I get a different result:

public static double CalculateBallVolume(double aRadius)
{
    double volume = (4 / 3) * Math.PI * Math.Pow(aRadius,3);

    return volume;
}

In particular, it appears that 4 / 3 does not give the same result as 4.0 / 3.0. Why not?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
  • 1
    When you divide two integers, you get an integer. What does `4/3` give you? – Pranav Hosangadi Jan 12 '23 at 05:25
  • 1
    (4.0 / 3.0) = 1.3 but (4 / 3) is 1, first one is ```Double``` second one is ```int``` – MichaelMao Jan 12 '23 at 05:27
  • 1
    See [Integer Division](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/arithmetic-operators#integer-division): "For the operands of integer types, the result of the / operator is of an integer type and equals the quotient of the two operands rounded towards zero:" – Idle_Mind Jan 12 '23 at 05:28
  • Welcome to Stack Overflow. Please read [ask] and note well that this is **not a discussion forum**. Although the issue here is commonly asked about (so this question will soon be closed as a duplicate), I [edit]ed the question to show how to ask with proper style for Stack Overflow. Please do not talk about yourself, your level of experience, etc. in questions - it's only a distraction. – Karl Knechtel Jan 12 '23 at 05:31
  • 2
    Note that @MichaelMao is wrong. If you decide 4.0 by 3.0 you get a number that can't be represented by a normal decimal number (1.33repeating). That there are numbers that can't be represented by simple real number digit strings (whether rational or like `pi`) is worth remembering as you learn about math on a computer. Computer-based _floating point_ numbers are not decimal, they are binary. There are an infinite number or _real_ numbers, but only a finite number of combinations or 32 or 64 bits. Do not be surprised when what you assume a number should be in wrong – Flydog57 Jan 12 '23 at 05:35
  • @Flydog57 there's `decimal` in C#, although it's also finite and not repeating – phuclv Jan 12 '23 at 07:26
  • In my comment, I use _decimal_ in the English (rather than computer science or .NET) sense. A decimal number is a base-10 number (as opposed to hexadecimal (base-16), octal (base-8) or binary (base-2) – Flydog57 Jan 12 '23 at 15:48

0 Answers0