Help please!

I'm beginner and I don't know what is wrong with my code, please help me to solve this problem

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
  #include "stdafx.h"
#include <iostream>

using namespace std;

// Funkcija mora da se deklarise pre koriscenja

void print_result(double n);
double factorial(double x);

int main() {
	double n = 0.0;

	cout << "Unesite broj ciji faktorijel zelita da izracunate i pritisnite ENTER: ";
	cin >> n;

	// Pozivanje funkcije print result()
	print_result (n);

	system("PAUSE");
	return 0;
}

// Definicija funkcije print_result

void print_result(double n) {
	cout << "Faktorijel zadatog broja je: " << factorial(n) << endl;
}

// Definicija funkcije koja izracunava faktorijel

double factorial(double x) {
	double p = 1.0;
	for (double i = 1.0; i <= x; i++)
		return p *= i;
}
can you please post what error you're getting from the compiler?
You don't really need a double type for factorials - it's always a whole number. I'd use int or long int. Also I'd use an int type for the for loop.

Instead of returning in the for loop, you want to accumulate the product in p, then return p after the for loop completes all its iterations.

1
2
3
4
5
6
int factorial(int x) {
	int p = 1;
	for (int i = 1; i <= x; i++)
		p *= i;
	return p;
}
Last edited on
The main problems seems to be that the for loop in your factorial function doesn't do anything.

1
2
3
4
5
double factorial(double x) {
	double p = 1.0;
	for (double i = 1.0; i <= x; i++)
		return p *= i;
}

is (almost) the same as
1
2
3
4
double factorial(double x) {
	double p = 1.0;
		return p *= 1.0;
}
and if x happens to be below 1.0 you'll get garbage or a crash because it won't execute the for loop once and therefore won't even call a return.
Do you see how the for loop is basically useless in its current state?

Think about where you want to return in your function, and what you want to do before you return.
hint: n! = n*(n-1)! AKA factorial(n) == n*factorial(n-1)
Last edited on
I solved a problem, thank you guys so much :D
Topic archived. No new replies allowed.