-
Factorial beginner
Hi all,
I lately started learning programming, mostly Java and a little bit of PHP too.
I've been tryin to figure out some school assignments. In one of these assignments I have to use factorial.
I googled it and here's what I came up with (we've got to use methods):
Code:
package Factorial2;
import java.util.Scanner; // not used
import java.io.PrintStream;
class Factorial2 {
int factorialofnumber;
PrintStream out;
Factorial2() {
out = new PrintStream(System.out);
}
void Factorial(int x) {
for (int p = 1; p <= x; p++) {
factorialofnumber *= p;
out.printf("Factorial:%.1f", factorialofnumber);
}
}
void Start(){
Factorial(5);
}
public static void main(String[] args) {
new Factorial2().Start();
}
}
Now, this doesn't work, but I don't see why. Can anyone of you guys help me on this one?
Thanks in advance.
-
Re: Factorial beginner
If you don't initialize a member variable (such as factorialofnumber) it is implicitly initialized to zero for you. You don't want that.
kind regards,
Jos
-
Re: Factorial beginner
Thanks. Now my method looks like this:
Code:
void Factorial(int x) {
int factorialofnumber = 1;
for (int p = 1; p <= x; p++) {
factorialofnumber *= p;
out.printf("Factorial:%.1f", factorialofnumber);
}
There's no need to make factorialofnumber global. It still doesn't work and I'm getting the same errors.
-
Re: Factorial beginner
What errors? We don't read minds. Copy and paste the full error messages you get.
-
Re: Factorial beginner
Hey,
I resolved the issue.
I used "%f" instead of "%d", while trying to output an integer.
Here's the code for if anyone has this problem in the future:
Code:
void Factorial(int x) {
int factorialofnumber = 1;
for (int p = 1; p <= x; p++) {
factorialofnumber *= p;
}
out.printf("Factorial is %d",factorialofnumber);