java - Method Returning Type Ignored -


i trying method made return value of x*y long. however, returning int. far know specifying in method header return long need done ?

i unable required result, missing?

code

public class returnpower  {      public long power(int x,int n)      {            int total = x * n;         if(x < 0 && n < 0)         {             system.out.println("x and/or n not positive");             system.exit(0);         }         return (total);      }      public static void main(string[] args)     {         returnpower power = new returnpower();          system.out.println(power.power(99999999,999999999));     } } 

output

469325057 

thanks

ben

no, it's returning long. it's you're performing arithmetic in 32-bit integer arithmetic first. @ how you're doing arithmetic:

int total = x * n; 

you're not storing result long, don't see how expect retain full long value. need total long - and you've got make 1 of operands long in order make multiplication occur in 64-bit.

to force multiplication occur in 64-bit arithmetic, should cast 1 of operands:

long total = x * (long) n; 

alternatively, rid of total variable - suggest performing argument validation before using parameters anyway:

public long power(int x, int n)  {        if (x < 0 && n < 0)     {         // use exceptions report errors, not system.exit         throw new illegalargumentexception("x and/or n negative");     }     return x * (long) n; } 

(additionally, isn't performing power operation in same way math.pow, example...)


Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -