How can I print a value declared with double?

I am doing an exercise to calculate the factorial of a number, using for. Everything is well except that I get a warning printing the result because I declared a variable factorial with double instead of int. Then I put %d to print the result but the format is wrong. What would be the best choice for long numbers? what would be the syntaxis to print it?

Thank you in advance.
It sounds like you are using the printf() C function. This is a C++ forum. If you want to calculate large factorials how about long long or unsigned long long? If you want to go even larger than that (arbitrarily large numbers), then an external library like Boost can help.

An example of a factorial with for loop in C++:

1
2
3
4
5
int n = 5;
int result = 1;

for (int i = n; i != 0; --i)
    result *= i;

or

1
2
3
4
5
int n = 5;
int result = 1;

for (int i = 1; i <= n; ++i)
    result *= i;

If you want to use double, then change int to double.

Using C++ printing it is as simple as this:
std::cout << result << '\n';
Last edited on
Didn't know about that. The course I am doing is C/C++ we compile in C++ using printf and:

#include <stdio.h>
#include <stdlib.h>

We always use printf and scanf. Maybe we will know how to do that with cout later as I only took 2 classes out of 9. The thing is I don't know which letter to use in scanf using long long or unsigned long or double since I only used int with %d and float with %f.
Last edited on
Google it. Google is your friend.
Found it. Solved.
That was fast... Google saves the day.
Topic archived. No new replies allowed.