// Fifth root of the sum of the squares of the first 100 ODD numbers
#include <iostream>
#include <cmath>
usingnamespace std;
int main()
{
int a=1;
int x=0;
double numbers [x];
double answer;
int repeat = 100;
cout << "This program finds the fifth root of the sum of the squares of x numbers." << endl;
cout << "How many odd numbers? ";
cin >> repeat;
cout << endl;
// for statement repeats the mapping process for how many odd numbers you want, in this case 100.
// x=array size and a=initial number and counts up from there
for (int n=0; n<repeat; n++)
{
numbers[x] = sqrt(a);
x+=1;
a+=2;
}
// adds all of the numbers in the array, based on the x variable
// that was used to create the array in the previous statement
for (int n=repeat; n>0; n--)
{
answer += numbers[x];
x-=1;
}
// display the result
cout << "The result is: " << answer << endl;
system ("pause");
return (0);
}
I haven't made it do the fifth root yet, but it is already giving me the wrong answer.
For some reason if I try 5, it is giving me 9.something... when I add the first 5 squares (sqrt1, 3, 5, 7, 9) on my calculator, I get 10.61.
ALSO, if I do a larger number, the entire code crashes.
#include <iostream>
#include <cmath>
#include <cstdlib>
usingnamespace std;
int main()
{
int a=1;
int count=0;
//double numbers [x];
double answer;
int repeat;
cout << "This program finds the fifth root of the sum of the squares of x numbers." << endl;
cout << "How many odd numbers? ";
cin >> repeat;
cout << endl;
double numbers[repeat];
// for statement repeats the mapping process for how many odd numbers you want, in this case 100.
// x=array size and a=initial number and counts up from there
for (int n=0; n<repeat; n++)
{
numbers[n] = sqrt(a);
a+=2;
count++;
}
// adds all of the numbers in the array, based on the x variable
// that was used to create the array in the previous statement
for (int n=count; n>0; n--)
{
answer += numbers[n-1];
//x-=1;
}
// display the result
cout << "The result is: " << answer << endl;
system ("pause");
return (0);
}
The problem is the way you are reading your 'numbers' array.
If you are doing 100 like your example, it reads the numbers into numbers[0] - numbers[99] and then increments x by 1 each time. In your next for loop it will then start reading at numbers[100] which doesn't have a value and will give undefined behavior (C++ doesn't check to see if you went out of bounds on an array).
There are several ways you could fix this by rearranging code, but a simple way is to change line 34 to answer += numbers[x - 1];
Another problem is you are declaring an "x" amount of values in your numbers array when x hasn't been defined yet which will cause strange behavior. So you will either have to change that to an actual number or switching to vectors might not be a bad idea either (which would also make the whole thing safer).