Jan 29, 2022 at 5:35pm UTC
How do you know that it does not return a value?
Jan 29, 2022 at 5:36pm UTC
i tried to run in visual studio but i did not work. it asks me to enter my cin value and after that it shows nothing
Jan 29, 2022 at 5:42pm UTC
Which line of code would show something?
You do get 'answer' on line 41 and do exactly nothing with it.
Jan 29, 2022 at 5:45pm UTC
the line 18 run correctly because it asks me to entre the nb_iteration and after that nothing happens
Jan 29, 2022 at 5:48pm UTC
i tried it with a void function . and i put cout << pi; instead of return it works perfectly
Jan 29, 2022 at 5:53pm UTC
ohhhh thank you so much. i thought that by calling the function the return will show up automatically.
Jan 29, 2022 at 6:11pm UTC
The Visual Studio has a
debugger . You could with it halt the execution of your program and read what values it has in memory at that point.
Remember that a program could be run from command line and the main() could call many functions and have many variables. Nothing is shown implictly.
The rand() and srand() are functions from C library. C++ library has <random> with much better options.
For example:
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
#include <iostream>
#include <random>
#include <iomanip>
using std::cout;
double getpi( size_t nb_iteration )
{
std::default_random_engine generator;
std::uniform_real_distribution<double > distribution( -1.0, 1.0 );
size_t compteur = 0;
for ( size_t i = 0; i < nb_iteration; ++i )
{
double x = distribution(generator);
double y = distribution(generator);
if (x * x + y * y < 1.0)
{
++compteur;
}
}
return (4.0 * compteur) / nb_iteration;
}
int main() {
size_t nb_iteration {};
cout << "entrer le nombre d'iteration " ;
std::cin >> nb_iteration;
double answer= getpi( nb_iteration );
cout << std::fixed;
cout << std::setprecision(6);
cout << answer << '\n' ;
}
Last edited on Jan 29, 2022 at 6:12pm UTC
Jan 29, 2022 at 7:50pm UTC
thank you so much guys for the help. appreciate it.