/***//**
* Fractionserial. Java
* There is a fractional sequence: 2/1, 3/2, 5/3, 8/5, 13/8, 21/13...
* Calculate the sum of the first 20 items of the series.
* @ Author Deng Chao (codingmouse)
* @ Version 0.2
* Development/test environment: jdk1.6 + eclipse SDK 3.3.2
*/
Public class fractionserial ...{
Public static void main (string [] ARGs )...{
/**//*
* Note: The variables involved in the calculation of series items must be declared as double type.
* To get the correct answer: 32.66026079864164;
* If it is declared as int type
* The value is automatically converted to the double type.
* If it is converted to the int type, the precision will be lost, resulting in computing completion.
* The result is a wrong answer: 21.
*/
// Calculate the first num of the Series
Int num = 20;
// Save the sum of the previous num items
Double sum = 0;
// X indicates the numerator, and y indicates the denominator.
Double X = 2, y = 1;
// The intermediate variable used for exchanging values
Double temp;
// Console input prompt
System. Out. println ("before this series" + num + "content :");
// Cyclically process each generated Series
For (INT I = 1; I <= num; I ++ )...{
// Print the content of the num before the sequence
System. Out. Print (INT) x + "/" + (INT) y );
// Print a comma (,) after the specified number of non-ending items to separate items
If (I! = Num )...{
System. Out. Print (",");
}
// Accumulate and save the values of the I items before the series
Sum + = x/y;
// The intermediate variable temp stores the current molecular Value
Temp = X;
// The X value is assigned to the sum of the current molecular value and the current denominator value, which constitutes the next part of the series.
X + = y;
// The Y value is assigned the Temp value of the intermediate variable, that is, the current item is the denominator of the next item in the series.
Y = temp;
}
// Outputs computing information on the console
System. Out. Print ("the sum of the preceding items:" + sum );
}
}