waltbaby315
asked on
How do I generate an array with the output of 1,0,0,0,0.....?
How do I generate an array with the output of 1,0,0,0,0.....?
public class chap7quiz9
{
public static void main(String[] args)
{
int a[] = new int[24];
for(int i = 0; i<24;i++)
{
a =1/(1+i);
System.out.println(0);
}
}
}
today230.JPG
public class chap7quiz9
{
public static void main(String[] args)
{
int a[] = new int[24];
for(int i = 0; i<24;i++)
{
a =1/(1+i);
System.out.println(0);
}
}
}
today230.JPG
Even if you type it proably wwhta you meant
a[i]=1/(1+i)
you'll get 1 for the first element
a[0] = 1/1;
but
a[1] = 1/2;
and when you assign to int you get truncation of the
decimal part, so it wioll
a[1] = 0;
and all of the rest the same
In order to print something sensible
you need to declare array a as float
This will give you reasonable numbers
(in addition you also had
System.out.println(0) in your original code
instead of
you need to declare array a as float
{
public static void main(String[] args)
{
float a[] = new int[24];
for(int i = 0; i<24;i++)
{
a[i] =1.0f/(1.0f+i);
System.out.println(a[i]);
}
}
}
This will give you reasonable numbers
(in addition you also had
System.out.println(0) in your original code
instead of
System.out.println(a[i]);)
Actually this is correct code
(forgot to chang int to float in array declaration)
(forgot to chang int to float in array declaration)
{
public static void main(String[] args)
{
float a[] = new float[24];
for(int i = 0; i<24;i++)
{
a[i] =1.0f/(1.0f+i);
System.out.println(a[i]);
}
}
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
a= 1/(1+i);
cannot work through compiler array cnnot be assihgned to integere or rather
integere to the arrai