Link to home
Start Free TrialLog in
Avatar of waltbaby315
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
Avatar of for_yan
for_yan
Flag of United States of America image

Your code as you pasted it cannot compile,
a= 1/(1+i);
cannot work through compiler array cnnot be assihgned to integere or rather
integere to the arrai
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

Open in new window

In order to print something sensible
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]);
}
}
}

Open in new window


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]);)

Open in new window


Actually this is correct code
(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]);
}
}
}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of for_yan
for_yan
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial