文档详情

算法第四版习题答案解析.doc

发布:2019-01-06约2.58万字共25页下载文档
文本预览下载声明
WORD格式可编辑 专业知识分享 1.1.1 给出以下表达式的值: a. ( 0 + 15 ) / 2 b. 2.0e-6 * 100000000.1 c. true false || true true 答案:a.7,b.200.0000002 c.ture 1.1.2 给出以下表达式的类型和值: a. (1 + 2.236)/2 b. 1 + 2 + 3 + 4.0 c. 4.1 = 4 d. 1 + 2 + 3 答案:a.1.618 b. 10.0 c.true d.33 1.1.3  编写一个程序,从命令行得到三个整数参数。如果它们都相等则打印equal,否则打印not equal。 public class TestUqual { public static void main(String[] args) { int a,b,c; a=b=c=0; StdOut.println(Please enter three numbers); a =StdIn.readInt(); b=StdIn.readInt(); c=StdIn.readInt(); if(equals(a,b,c)==1) { StdOut.print(equal); } else { StdOut.print(not equal); } } public static int equals(int a ,int b , int c) { if(a==bb==c) { return 1; } else { return 0; } } } 1.1.4 下列语句各有什么问题(如果有的话)? a. if (a b) then c = 0; b. if a b { c = 0; } c. if (a b) c = 0; d. if (a b) c = 0 else b = 0; 答案:a. if (a b) c = 0; b. if (a b) { c = 0; } 1.1.5  编写一段程序,如果double 类型的变量x 和y 都严格位于0 和1 之间则打印true,否则打印false。 public class TestUqual { public static void main(String[] args) { double x; double y; x=StdIn.readDouble(); y=StdIn.readDouble(); StdOut.print(compare(x) compare(y)); } public static boolean compare(double x) { If(x0x1) returen ture; else return false; } } 1.1.6 下面这段程序会打印出什么? int f = 0; int g = 1; for (int i = 0; i = 15; i++) { StdOut.println(f); f = f + g; g = f - g; } 答案:0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 1.1.7 分别给出以下代码段打印出的值: a. double t = 9.0; while (Math.abs(t - 9.0/t) .001) t = (9.0/t + t) / 2.0; StdOut.printf(%.5f\n, t); b. int sum = 0; for (int i = 1; i 1000; i++) for (int j = 0; j i; j++) sum++; StdOut.println(sum); c. int sum = 0; for (int i = 1; i 1000; i *= 2) for (int j = 0; j 1000; j++) sum++; StdOut.println(sum); 答案:a.3.00009 b.499500 c. 10000 1.1.8 下列语句会打印出什么结果?给出解释。 a. System.out.println(b); b. System.out.println(b + c); c. System.out.println((char) (a + 4)); 答案:a. b b. 197
显示全部
相似文档