0

I hav to write a simple program in bluej that computes and prints the sum of the reciprocals of the first 10 positive integers. My code is

public static void main (String[] args){ 

System.out.println(1/1 + 1/2 + 1/3 + 1/4 + 1/5 + 1/6 + 1/7 + 1/8 + 1/9 +1/10); }

It outputs the number 1. Can someone please explain why and tell me what the code should be? My teacher said I shouldn’t use variables or anything.

Andrew Lin
  • 11
  • 1
  • 5

1 Answers1

0

Try 1.0/1.0 + 1.0/2.0 + etc.

The reason is the compiler interprets 1/2 as an integer divided by an integer which will return an integer (the floor of the true value). 1.0/2.0 is interpreted as a float/float which will return a float.

Google 'C integer arithmetic' for more.

rho
  • 33
  • 6