-9

May i know what is the difference between these two methods?

static int cube(int num)
{
  int result = num * num * num;
  return result;
}
static void cube(int num)
{
  Console.WriteLine(Math.Pow(num,3));
}
Jin En Ng
  • 1
  • 3
  • 2
    The biggest difference is that the first one _returns_ the result, so that it may be used further by the _program_ (specifically in the calling code: e.g. `Console.WriteLine(2 * cube(3))` works fine in the first case, but not in the second). The second one _displays_ the result to the user, returning nothing (so the calling code will not be able to use it). – Amadan Aug 10 '23 at 02:22
  • I'm going to assume that the method signature and the method's return is _not_ the actual question, but whether you should use multiple multiplication operators or the Pow method. My response: does it matter? They both give you the same answer, and (assuming you have executed the code), run in a reasonable amount if time. Is there any reason why you're questioning it? – gunr2171 Aug 10 '23 at 02:27
  • Another subtle difference is Pow returns [double](https://learn.microsoft.com/en-us/dotnet/api/system.double), while multiplying [integers](https://learn.microsoft.com/en-us/dotnet/api/system.int32) still gives you integer. Read up on https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/integral-numeric-types and https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/floating-point-numeric-types to see which one fits the specific use case you're dealing with. – Martheen Aug 10 '23 at 02:31
  • @Amadan thank you so much for your comment. It helps me to enhance my understanding. – Jin En Ng Aug 10 '23 at 02:36
  • I'm pretty sure that two integer multiplications will be significantly faster than what `double Math.Pow(double, double)` does. I'm also pretty sure that you won't notice unless you do an awful lot of them. Also, integer multiplication is exact. When you are working in double-land, inexactness can slip in – Flydog57 Aug 10 '23 at 04:42

0 Answers0