程序题
1.计算1/1+1/2+1/3+….+1/100的值。
代码如下:
public class Demo1 {
public static void main(String[] args) { double sum = 0; double n = 1;
while (n <= 100) { sum += 1 / n; n++; }
System.out.println(sum);
System.out.println(\); System.out.println(\);
System.out.println(\徐延迟\);
} }
2.设计计算阶乘的函数为:m (n) =n! 。设计一个计算阶乘的方法和相应的类,并利用这个类计算4的阶乘。
代码如下:
public class Demo2 {
public static int jieCheng(int n) { if (n == 1 || n == 0)
1
return n; else
return n * jieCheng(n - 1); }
public static void main(String[] args) { System.out.println(jieCheng(4));
System.out.println(\); System.out.println(\);
System.out.println(\徐延迟\);
} }
3.编写一个应用程序,可以计算result=1!+2!+…+100!。并输出。
代码如下:
public class Demo3 {
public static void main(String[] args) { System.out.println(sum(100));
System.out.println(\); System.out.println(\);
System.out.println(\徐延迟\);
}
public static int sum(int n){ int sum=0; while(n>=0){
sum=sum+jiecheng(n); n--; }
return sum; }
public static int jiecheng(int n){ if(n==1||n==0){ return n; }else{
2
return n*jiecheng(n-1); } } }
4. 将整数数组a赋初值(含8个元素),并求出a中的最大元素和最大元素的下标。
代码如下:
public class Demo4 {
public static void main(String[] args) { int arr[] = { 9, 5, 8, 6, 4, 2, 3, 18 }; int maxIndex = 0, max = arr[0];
for (int i = 0; i < arr.length; i++) { if (arr[i] > max) { maxIndex = i; } }
System.out.println(\最大的元素为:\ + arr[maxIndex]
+ \其下标为:\ + maxIndex);
System.out.println(\); System.out.println(\); System.out.println(\徐延迟\);
} }
5. 从一堆数组中找出最大的元素和最小的元素
3
代码如下;
public class Demo5 {
public static void main(String[] args) {
int arr[] = { 33, 56, 9, 46, 99, 5656, 5, 6, 4, 9 };
int max, min;
max = min = arr[0];
for (int i = 0; i < arr.length; i++) { if (arr[i] > max) { max = arr[i]; }
if (arr[i] < min) { min = arr[i]; } }
System.out.println(\最大值为:\ + max + \最小值为:
\ + min);
System.out.println(\); System.out.println(\);
System.out.println(\徐延迟\);
} }
6.计算二维数组中各行元素之和并查找其值最大的那个行,假定元素值都为正整数。
4
代码如下:
public class Demo6 {
public static void main(String[] args) {
int[][] arr = { { 11, 23, 66, 77, 5 }, { 1, 23, 5, 66, 4 },
{ 5, 6, 8, 9 }, { 1, 3, 4 } }; int sum = 0; int maxSum = 0; int indexI = 0;
for (int i = 0; i < arr.length; i++) { int j;
for (j = 0; j < arr[i].length; j++) { sum += arr[i][j];
}
if (sum > maxSum) { maxSum = sum; indexI = i;
}
System.out.println(\第\ + (i+1) + \行的数组之后
为:\ + sum);
5
}
System.out.println(\最大一行为:\ + (indexI+1));
System.out.println(\); System.out.println(\);
System.out.println(\徐延迟\);
百度搜索“77cn”或“免费范文网”即可找到本站免费阅读全部范文。收藏本站方便下次阅读,免费范文网,提供经典小说综合文库Java编程题在线全文阅读。
相关推荐: