习题3
1. 下列程序的输出结果是什么?
public class E
{
public static void main (String args[])
{
char x = '你', y = 'e', z = '吃';
if(x > 'A')
{
y = '爱';
z = '情';
}
else
{
y = '我';
}
z = '她';
System.out.println(" " + x + y + z);
}
}
答:
输出结果是:你爱她
2. 下列程序的输出结果是什么?
public class E {
public static void main(String args[]) {
char c = '\0';
for (int i = 1; i <= 4; i++) {
switch ( i ) {
case 1:
c = 'b';
System.out.print( c );
case 2:
c = 'e';
System.out.print( c );
break;
case 3:
c = 'p';
System.out.print( c );
default:
System.out.print("!");
}
}
}
}
答:
输出结果是:beep!!
3. 编写应用程序,求1!+2!+….+10!。
// 目的: 计算1!+2!+...的前10项的和
class SumOfFactorial
{
public static void main (String args[])
{
long x = 1, sum = 0;
for(int i = 1; i < 11; i++)
{
x *= i;
sum += x;
if(i != 10) System.out.print(i + "!+");
else System.out.print(i + "!");
}
System.out.println("=" + sum);
}
}
运行程序,输出结果为:
1!+2!+3!+4!+5!+6!+7!+8!+9!+10!=4037913
4. 编写一个应用程序,求100以内的全部素数。
// 目的: 求100以内所有素数
public class PrimeNumber
{
public static void main (String args[])
{
int x, i;
for(x = 2; x <= 100; x++)
{
for(i = 2; i <= x / 2; i++)
{
if(x % i == 0) break;
}
if(i > x / 2) System.out.print(x + " ");
}
}
}
运行程序,输出结果是:
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
5. 分别用do-while和for循环计算1+1/2!+1/3!+1/4!+….的前20项和。
// 目的: 计算1+1/2!+1/3!+...前20项的和
public class SumOfSequence
{
public static void main (String args[])
{
double x = 1, sum = 0;
for(int i = 1; i <= 20; i++)
{
x *= 1.0 / i;
sum += x;
}
System.out.println("sum=" + sum);
}
}
运行程序,输出结果是:
sum=1.7182818284590455
6. 一个数如果恰好等于它的因子之和,这个数就称为“完数”。编写应用程序,求1000之内的所有完数。
// 目的: 求1000以内的完数
public class PerfectNum
{
public static void main (String args[])
{
int i, j ,sum;
for(i = 2; i < 1000; i++)
{
sum = 0;
for(j = 1; j < i - 1; j++)
{
if(i % j == 0) sum +=j;
}
if(i == sum) System.out.print(i + " ");
}
}
}
运行程序,输出结果是:
6 28 496
7. 编写应用程序,分别使用while循环和for循环计算8+88+888+…前10项之和。
// 目的: 计算8+88+888+...前10项的和
public class SumFactorial
{
public static void main (String args[])
{
long x = 8, sum = 0;
for(int i = 0; i < 10; i++)
{
sum += x;
x = x * 10 + 8;
}
System.out.println(sum);
}
}
运行程序,输出结果是:9876543200
8. 编写应用程序,输出满足1+2+3+…+n<8888的最大正数n。
// 目的: 输出满足1+2+3+...+n<8888的最大正数n
public class SumF {
public static void main(String args[]) {
int sum = 0, n = 1;
while (sum < 8888) {
sum += n;
n++;
}
n -= 2;
System.out.println( n );
}
}
运行程序,输出结果是:132
总结:这次看书+上机调试+做题总共花了我5个小时又20分钟,其中从20:00到 22:20为看书+上机调试例程时间,22:20到第二天01:00为做题时间,中间出去上了个吃了个宵夜,花了我10来分钟,另外上网找什么是因子时,来上到雅虎网不小心点了一个标题很吸引人的链接,然后就被谋杀了10几分钟,心痛啊。本来不打算通宵的,但是精神状态实在太好了,于是就一鼓作气,在看完第三章后,把没做的题目全部做完了。
做题过程中遇到了一些小问题,如第5题的 x += 1.0/i假如这里不是使用1.0而是使用1/i则会导致输出结果永远是1.0,因为1/i除号两边都是整数,故所得结果永远是0,但是我们要的是整个小数,所以必须得将除号两边的操作数至少一个变为浮点数,这里我是直接用1.0代替1。还有其它的方法,细心的朋友完全可以看出来的。
我还遇到另外一个很郁闷的问题就是,做第4题时,我已经写出了正确的算法了,可是当我把它写成程序时,却把 if(x % i == 0) break;里的判断条件写成了 i % 2 == 0,怎么也看不出来是哪里错了,没法,我只好启动netbeans来单步调试监控各个关键变量,还是没有看出来,只好对照课本里相同的例子,一句句的比较,才发现判断条件写错了,我的妈呀。我再看看我写程序前的分析算法,我明明写对了的,可是却打错了,这种低级的错误以后希望少犯或者不犯。
今天很有成就,希望明天可以继续。
第2题和第8题的错误已经修改了,多谢楼下朋友。