JAVA实现求斐波那契数列的前40项的和等题
1.求斐波那契数列的前40项的和
import java. util. Scanner;
public class Fibonacci {
public static void main ( String[ ] args) {
int i = 1 ;
int firstNum = 1 ;
int secondNum = 1 ;
int preNum = 1 ;
int lastNum = 1 ;
int lastLastNum = 0 ;
int sum = 0 ;
Scanner scanner = new Scanner ( System. in) ;
System. out. println ( "请输入你想求和到第多少项: " ) ;
int input = scanner. nextInt ( ) ;
while ( i <= input) {
lastLastNum = preNum + lastNum;
preNum = lastNum;
lastNum = lastLastNum;
System. out. print ( lastLastNum + " " ) ;
i++ ;
}
}
}
public class Fibonacci {
public static void main ( String[ ] args) {
int [ ] arr = new int [ 40 ] ;
arr[ 0 ] = 1 ;
arr[ 1 ] = 1 ;
int sum = 0 ;
for ( int i = 2 ; i < arr. length; i++ ) {
arr[ i] = arr[ i - 2 ] + arr[ i - 1 ] ;
}
for ( int i : arr) {
System. out. print ( i + " " ) ;
}
}
}
2.用for循环产生20个随机数(10-20)
import java. util. *;
public class Ran {
public static void main ( String[ ] args) {
Random random = new Random ( ) ;
for ( int i = 1 ; i <= 20 ; i++ ) {
int r = random. nextInt ( 10 ) + 10 ;
System. out. println ( r) ;
}
}
}
3.输入一个数字,求他是几位数,并且顺序输出,逆序输出
import java. util. Scanner;
public class InputNumber {
public static void main ( String[ ] args) {
Scanner scanner = new Scanner ( System. in) ;
int input = scanner. nextInt ( ) ;
int count = 0 ;
int temp = input;
int temp1 = temp;
while ( input!= 0 ) {
input = input/ 10 ;
count++ ;
}
System. out. println ( "是" + count + "位数" ) ;
while ( count >= 1 ) {
count-- ;
System. out. print ( temp/ ( int ) ( Math. pow ( 10 , count) ) + " " ) ;
temp = ( int ) ( temp % ( Math. pow ( 10 , count) ) ) ;
}
System. out. println ( ) ;
while ( temp1!= 0 ) {
System. out. print ( temp1 % 10 + " " ) ;
temp1 = temp1/ 10 ;
}
}
}
4.求一个数字的二进制数有几个1
import java. util. Scanner;
public class Test4 {
public static void main ( String[ ] args) {
Scanner scanner = new Scanner ( System. in) ;
int input = scanner. nextInt ( ) ;
int count = 0 ;
while ( ( input & 1 ) != 0 ) {
input >>>= 1 ;
count++ ;
}
System. out. println ( count) ;
}
}
2018.10.14/周天
by 922