i'm new site , looking help. i'm trying design program take input of numbers user, store array, , format them correctly 3 columns. however, can't seem figure out why inputs aren't formatting correctly.
#include <stdio.h> int main() { int x=0; float num[100]; /* loop receiving inputs user , storing in array */ (x=0; x<=100; x++) { scanf("%f", &num[x]); printf("%7.1lf%11.0lf%10.3lf", num[x], num[x+1], num[x+2]); //printf("%f %f %f\n", num[0], num[1], num[2]); } return 0;
problems see:
use of incorrect range in
for
loop. givenfloat num[100];
the maximum valid index
99
. hence,for
loop needs be:for (x=0; x < 100; x++) // x < 100 not x <= 100
using array elements before initialized.
printf("%7.1lf%11.0lf%10.3lf", num[x], num[x+1], num[x+2]);
nothing has been read
num[x+1]
,num[x+2]
. hence, going garbage values.accessing
num
using out of bounds array indices.accessing
num[x]
,num[x+1]
, ,num[x+2]
makes sense ifx+2
less or equal97
.
my suggestion:
use 2 loops. in first loop, read data. in second loop, write out data.
for (x=0; x < 100; x++) // using 100 here. { scanf("%f", &num[x]); } (x=0; x < 98; x++) // using 98 here. { printf("%7.1lf%11.0lf%10.3lf", num[x], num[x+1], num[x+2]); }
update, in response comment op
change print loop to:
for (x=0; x < 98; x += 3) // increment x 3 { printf("%7.1lf%11.0lf%10.3lf", num[x], num[x+1], num[x+2]); }
Comments
Post a Comment