A little question about c language

nenyan
Messages
67
Reaction score
0
/*find abs value of an array*/
int absv(double *a, int n)
{
int i;
for(i=0;i<n;i++)
{if (a<0)
a=-a;

}

}


int main()
{
double a[7];
int i,j;
for(i=0;i<7;i++)
scanf("%lf\n",&a);
absv(a,7);
for(j=0;j<7;j++)
printf("%e\n",a[j]);

printf("%d,%d",i,j);

}

The result is weird. I can inpute 8 numbers but it output 7 numbers.
You can see both i and j is 7.
Why I can inpute a[7], but I can not output it?
 
Physics news on Phys.org
nenyan said:
/*find abs value of an array*/
int absv(double *a, int n)
{
int i;
for(i=0;i<n;i++)
{if (a<0)
a=-a;

}

}


int main()
{
double a[7];
int i,j;
for(i=0;i<7;i++)

So i goes from 0 to 6, 7 values, not 8. You can type all the numbers you like, but this will read in only 7 numbers and then output 7 numbers. If you want to do 8 numbers use either
"for (i= 0;i<= 7;i++)" or "for (i= 0;i,< 8;i++)".

scanf("%lf\n",&a);
absv(a,7);
for(j=0;j<7;j++)
printf("%e\n",a[j]);

printf("%d,%d",i,j);

}

The result is weird. I can inpute 8 numbers but it output 7 numbers.
You can see both i and j is 7.
Why I can inpute a[7], but I can not output it?

You may have typed 8 numbers but you didn't input a[7] because i only went up to 6.
 
Thanks.
scanf("%lf\n",&a);
I should get rid of "\n".
 
In addition to Halls's advice, be sure to change the declaration of a to

double a[8];

Otherwise you will overflow the array with possibly disastrous results when you input a[7].
 
oh, yes.
awkward said:
In addition to Halls's advice, be sure to change the declaration of a to

double a[8];

Otherwise you will overflow the array with possibly disastrous results when you input a[7].
 

Similar threads

Replies
8
Views
2K
Replies
3
Views
1K
Replies
1
Views
2K
Replies
1
Views
10K
Replies
25
Views
2K
Replies
4
Views
1K
Back
Top