One issue is this:
double A[c], B[c], C[c];
This is not valid C++, as arrays must have constant expressions to denote the number of entries. You're using an extension offered by your compiler, namely Variable Length Arrays (VLA). The issue is more than likely you're blowing out the stack space due to the arrays being too large.
Instead of this, use something that is valid C++, namely std::vector:
long long int n;
cin >> n;
long long int c = n - 1;
std::vector<double> A(c), B(c), C(c);
However, please note that a std::vector
is limited to std::vector::max_size()
elements, thus it is possible that the value you enter for n
may be too large to store the elements. Reconsider whether you want to go beyond the max_size()
value.
In addition, you are accessing elements out of bounds. This is another area where using std::vector
is advantageous over arrays.
for (long long int i = 0; i <= c; i++) {
A.at(i) = ((double) rand() / (double) (RAND_MAX));
B[i] = ((double) rand() / (double) (RAND_MAX));
C[i] = (double) A[i] * B[i];
printf("%d %.15f\n",i, C[i]);
}
You will see that when i == c
, the call to A.at()
is guaranteed to throw an std::out_of_range
exception, denoting that you have gone out of bounds with the index i
. An array cannot report errors like this with any consistency, as going out-of-bounds of an array is undefined behavior (the code may "work", may crash, etc.).
There is another issue, and it's this:
printf("%d", sum);
Since sum
is a double
, giving printf
a variable type that does not match the format specifier is undefined behavior. More than likely, you will see wild numbers being printed. The format specifier, %d
, requires an int
type, not a double
. So the correction would be this:
printf("%lf", sum);
But since you're using C++, you should simply use std::cout
, as it is typesafe and will not have you get into this type of trouble:
std::cout << sum;
When you remove all of the errors and make the corrections describe, here is a live example showing the output.
In addition, here is an alternative that uses the STL algorithm functions that is much shorter than the code you have now, and does not need to declare 3 vectors (only one vector needs to be declared):
Example using STL algorithms