Reputation: 13
I'm doing this exercise where I need to show to the user a list of sequence from 1 to 1000 and I have to make:
But I'm having a few troubles here where it doesn't shows me the numbers being inserted in my list (array)... It only displays me a "0". What am I doing wrong here? Can't find it... Thanks.
#include <stdio.h>
#include <stdlib.h>
int main() {
int i;
float a;
float array[1000] = {1};
a = 1;
for (i = 0; i <= 1000; i++) {
array[i+1] = 2 * a + (a + 1);
printf("\nSequencia:%d - %.2f", i, array);
}
system("pause");
return 0;
}
Upvotes: 0
Views: 405
Reputation: 67
Use BUFFER_SIZE
macro to not overflow because of your condition "i <= 1000", array[1000] is between 0 and 999, your code :array[i + 1]
, will overflow at array[1000] and array[1001].
You are printing array
and not array[index]
.
#include<stdio.h>
#include<stdlib.h>
#define BUFFER_SIZE 1000
int main(void)
{
float a = 1;
float array[BUFFER_SIZE] = {1};
printf("\nSequencia: %d - %.2f", 0, array[0]);
for (int i = 1; i < (BUFFER_SIZE - 1); i++) {
//Maybe you are looking for : a = 2 * a + (a + 1);
array[i] = 2 * a + (a + 1); //Then : array[i] = a;
printf("\nSequencia: %d - %.2f", i, array[i]);
}
system("pause");
return 0;
}
You may not be able to print everything with float, so you should use bigger types as double or long double (extreme case : strings).
Doing my best with my english level sorry ^^.
Upvotes: 1
Reputation: 386406
a
instead of the correct value.array
instead of array[i]
.Enable your compiler's warnings!!! It would have caught some of these.
Fixed:
size_t n = 1000;
float array[n];
array[0] = 1;
printf( "%zu - %f\n", 0 + 1, array[ 0 ] );
for ( size_t i = 1; i < n; ++i ) {
array[ i ] = 2 * array[ i - 1 ] + 2;
printf( "%zu - %f\n", i + 1, array[ i ] );
}
There's a final problem: The 1000th number of the sequence will be extremely large. Given a[i]=2*a[i-1]
, the 1000th number would be 2999. You have a[i]=2*a[i-1]+2
which is even larger. These are huge numbers. For comparison, there are about 1080 ≈ 2266 atoms in the visible universe.
So huge, in fact, that numbers that large can't be stored in a float
on an x86 or x86-64. Moving to larger type could help, but it won't give the precision needed. Therefore, you'll need an arbitrary precision library.
Upvotes: 1