Returning output of "Floating point exception (core dumped)"

I'm trying to have the user input the number of particles (N), and return random x, y, and z values for each particle. But i have to limit the velocity of each particle by the equation 200 >= x^2 + y^2 + z^2, basically limiting the magnitude to no higher than 200 for each particle. My code so far is just returning:
Enter the number of particles:
3
The velocity of the particles are
x: y: z:
Floating point exception (core dumped)
I do not know if my code does what is asked and how to fix the problem. Any help would be greatly appreciated.


[code]
#include <cstdlib>
#include <iostream>
#include <cmath>
#include <ctime>
using namespace std;

int main(){
int N , x, y, z, vt;
cout << "Enter the number of particles: \n";
cin >> N;
cout << "The velocity of the particles are\nx: y: z:\n";
std::srand(time(NULL));
for(int i = 1; i <= N; i++){

int x = std::rand() % vt;
int y = std::rand() % vt;
int z = std::rand() % vt;
vt = 200 - (x*x+y*y+z*z);
cout << x; y; z;

}
}
Your variable vt is doesn't have a value when do perform these.
1
2
3
int x = std::rand() % vt;
int y = std::rand() % vt;
int z = std::rand() % vt;

That's why it's giving seg faults.
Thank you, but how would i limit the x, y, and z values to the magnitude of the equation then?
Something like this, perhaps:

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
38
#include <iostream>
#include <random>
#include <cmath>
#include <algorithm>
#include <iomanip>

// random x, y, z limited by max >= x^2 + y^2 + z^2
void random_clamped( int& x, int& y, int& z, int max = 200 )
{
    static std::mt19937 rng( std::random_device{}() ) ;

    x = std::uniform_int_distribution<int>( 0, std::sqrt(max) )(rng) ; 
    y = std::uniform_int_distribution<int>( 0, std::sqrt( max -= x*x ) )(rng) ;
    z = std::uniform_int_distribution<int>( 0, std::sqrt( max - y*y ) )(rng) ;

    int temp[] = { x, y, z } ;
    std::shuffle( temp, temp+3, rng ) ;
    x = temp[0] ;
    y = temp[1] ;
    z = temp[2] ;
}

int main()
{
    int N = 50 ;

    int x, y, z ;
    while( N-- )
    {
        random_clamped( x, y, z, 200 ) ;
        
        std::cout << "x: " << std::setw(2) << x
                  << "   y: " << std::setw(2) << y
                  << "   z: " << std::setw(2) << z
                  << "   x*x + y*y + z*z == " << std::setw(3) << x*x + y*y + z*z << '\n' ;

    }
}

http://coliru.stacked-crooked.com/a/e7fbbcdac159344b
Topic archived. No new replies allowed.