+ 3
HELPPPP in Java please calculator potencies
Hello, I have a problem. Iâm currently trying to do a simple calculator in java as homework. Iâve made a GUI with JButtons, JLabels and JNumberFields. I added multiplication, division, addition and subtraction to my calculator and itâs working without any problems. Now my task is to add potency calculation to my calculator with a for loop. But I donât know how to do this. I began to write a code. Can someone help me please? https://code.sololearn.com/c2a0z7khZ4f1/?ref=app
13 Respostas
+ 6
Pauline 3^4 is 81. It is right.
exponent - 1 means (4-1 = 3). It is the limit of the for loop.
outcome = 1;
--> outcome = outcome * base (the loop have to run 4 times; i from 0 to 3)
outcome = base
--> the loop have to run only 3 times (i from 0 to 2)
+ 6
2^5 means 2*2*2*2*2 (5 times)
3^2 means 3*3 (2 times)
int base; //5
int exponent; //3
//5^3
int outcome = base; //5
//so you have to multiply outcome * base two times --> limit for your for loop = exponent - 1
for (int i = 0; i < exponent-1; i++){
outcome*= base;
}
i = 0 --> outcome = 25
i = 1 --> outcome = 125 = 5^3
+ 6
+ 6
You can also use math.pow.
Import java.util.Math;
int outcome = (int) Math.pow (base, exponent);
Edit: But you have to use a for loop. But with this method you can check if your for loop works.
+ 5
Pauline your welcome :)
+ 5
Okay dann auf deutsch:
Eine for loop Schleife hat einen Startwert, eine Bedingung wie lange sie laufen soll und was mit meinem Startwert passieren soll
For (int i = 0; i < ende; i++)
Angenommen ich habe die Basis 3 und den Exponenten 4;
3*3*3*3
Wenn ich den Ausgangswert von Outcome auf 1 setze, muss ich als Grenze den Exponenten wÀhlen.
For (int i = 0; i < exponent; i++){
Outcome = outcome * base
oder outcome*=base;
}
Wenn ich aber outcome = base wÀhle, spare ich mir eine Multiplikation. Also ist die Grenze exponent - 1
+ 2
its not working the outcome if i have 3^4 is 9
+ 2
ah okey now i understand it thank you đ
+ 1
Iâll try it. Thank you đ€
+ 1
its working thank you soooooo muchđđ€
+ 1
no the outcome is 81. what does the -1 behind exponent mean
+ 1
also was macht die -1 hinter dem exponent, fĂŒr was ist die gut
+ 1
ja ich habe es verstanden. es funktioniert jetzt alles danke đ€