快学scala第二章习题答案
2.-第二章课后习题及答案
2.-第二章课后习题及答案D3. (Q4) What information is used by a processrunning on one host to identify a process running on another host?Answer: The IP address of the destination host and the port number of the destination socket.4. (Q6) Referring to Figure 2.4, we see thatnone of the application listed in Figure2.4 requires both no data loss and timing.Can you conceive of an application that requires no data loss and that is also highly time-sensitive?Answer: There are no good example of an application that requires no data loss and timing. If you know of one, send an e-mail to the authors5. (Q9) Why do HTTP, FTP, SMTP, and POP3 run on top of TCP rather than on UDP?Answer: The applications associated with those protocols require that all application data be received in the correct order and without gaps. TCP provides this service whereas UDP does not.6. (Q11) What is meant by a handshaking protocol?Answer: A protocol uses handshaking if the two communicating entities first exchange control packets before sending data to each other. SMTP uses handshaking at the application layer whereas HTTP does not.7. (Q13) Telnet into a Web server and senda multiline request message. Include inthe request message the If-modified-since:header line to force a response message with the 304 Not Modified status code.Answer: Issued the following command (in Windows command prompt) followed by the HTTP GET message to the “” web server:> telnet 80Since the index.html page in this web server was not modified since Fri, 18 May 2007 09:23:34 GMT, the following output was displayed when the above commands were issued on Sat, 19 May 2007. Note that the first 4 lines are the GET message and header lines input by the user and the next 4 lines (starting from HTTP/1.1 304 Not Modified) is the response from the web server.8. (Q14) Consider an e-commerce site thatwants to keep a purchase record for each of its customers. Describe how this can be done with cookies.Answer: When the user first visits the site, the site returns a cookie number.This cookie number is stored on the user’s host and is managed by the browser.During each subsequent visit (and purchase), the browser sends the cookie number back to the site. Thus the site knows when this user (more precisely, this browser) is visiting the site.9. (Q15) Suppose Alice, with a Web-basede-mail account (such as Hotmail or gmail), sends a message to Bob, who accesses his mail from his mail server using POP3.Discuss how the message gets from Alice’s host to Bob’s host. Be sure to list theseries of application-layer protocols that are used to move the message between the two hosts.Answer: Message is sent from Alice’s host to her mail server over HTTP. Alice’s mail server then sends the message to Bob’s mail server over SMTP. Bob then transfers the message from his mail server to his host over POP3.10. (Q10) Recall that TCP can be enhancedwith SSL to provide process-to-process security services, including encryption.Does SSL operate at the transport layer or the application layer? If the application developer wants TCP to be enhanced with SSL, what does the developer have to do?Answer: SSL operates at the application layer. The SSL socket takes unencrypteddata from the application layer, encrypts it and then passes it to the TCP socket. If the application developer wants TCP to be enhanced with SSL, she has to include the SSL code in the application.11. (Q16) Print out the header of an e-mailmessage you have recently received. How many Received: header lines are there?Analyze each of the header lines in the message.Answer: from 65.54.246.203 (EHLO ) Received:(65.54.246.203) bywith SMTP; Sat, 19 May 200716:53:51 -0700from ([65.55.135.106]) by Received: with MicrosoftSMTPSVC(6.0.3790.2668); Sat, 19 May 2007 16:52:42 -0700Received: from mail pickup service by with MicrosoftSMTPSVC; Sat,19 May 200716:52:41 -0700Message-ID:<BAY130-F26D9E35BF59E0D18A819AFB9310@p hx.gbl>Received: from 65.55.135.123 byby130fd.bay130.hotmail.msn.com with HTTP; Sat, 19 May 200723:52:36 GMTFrom: "prithula dhungel"<prithuladhungel@>To: prithula@Bcc:Subject: Test mailDate: Sat, 19 May 2007 23:52:36 +0000Mime-Version:1.0Content-Type: Text/html; format=flowedReturn-Path: prithuladhungel@Figure: A sample mail message headerReceived: This header field indicates the sequence in which the SMTP servers send and receive the mail message including the respective timestamps.In this example there are 4 “Received:”header lines. This means the mail message passed through 5 different SMTP servers before being delivered to the receiver’s mail box. The last (forth) “Received:” heade r indicates the mail message flow from the SMTP server of the sender to the second SMTP server in the chain of servers. The sender’s SMTP server is at address 65.55.135.123 and the second SMTP server in the chain is . The thir d “Received:” header indicates the mail message flow from the second SMTPserver in the chain to the third server, and so on.Finally, the first “Received:” header indicates the flow of the mail message from the forth SMTP server to the last SMTP server (i.e. the receiver’s mail server) in the chain.Message-id: The message has been given this numberBAY130-F26D9E35BF59E0D18A819AFB9310@ph x.gbl(by. Message-id is a unique string assigned by the mail system when the message is first created.From: This indicates the email address of the sender of the mail. In the given example, the sender is prithuladhungel@To: This field indicates the email address of the receiver of the mail. In the example, the receiver is prithula@Subject: This gives the subject of the mail (if any specified by the sender). In the example, the subject specified by the sender is “Test mail”Date: The date and time when the mail was sent by the sender. In the example, the sender sent the mail on 19th May 2007, at time 23:52:36 GMT.Mime-version: MIME version used for the mail. In the example, it is 1.0.Content-type: The type of content in the body of the mail message. In the example, it is “text/html”.Return-Path: This specifies the emailaddress to which the mail will be sent if thereceiver of this mail wants to reply to the sender. This is also used by the sender’s mail server for bouncing back undeliverable mail messages of mailer-daemonerror messages. In the example, the return path is“prithuladhungel@”.12. (Q18) Is it possible for anorganization’s Web serve r and mail server to have exactly the same alias fora hostname (for example, )? Whatwould be the type for the RR that contains the hostname of the mail server?Answer: Yes an organization’s mail server and Web server can have the same alias for a host name. The MX record is used to map the mail server’s host name to its IP address.13. (Q19) Why is it said that FTP sends control information “out-of-band”?Answer: FTP uses two parallel TCP connections, one connection for sending control information (such as a request to transfer a file) and another connection for actually transferring the file. Because the control information is not sent over the same connection that the file is sent over, FTP sends control information out of band.14. (P6) Consider an HTTP client that wantsto retrieve a Web document at a given URL.The IP address of the HTTP server is initially unknown. What transport and application-layer protocols besides HTTP are needed in this scenario?Answer:Application layer protocols: DNS and HTTPTransport layer protocols: UDP for DNS;TCP for HTTP15. (P9) Consider Figure2.12, for whichthere is an institutional network connected to the Internet. Suppose that the average object size is 900,000 bits and that the average request rate from the institution’s browsers to the origin servers is 10 requests per second.Also suppose that the amount of time it takes from when the router on the Internet side of the access link forwards an HTTP request until it receives the response is two seconds on average (see Section 2.2.5). Model the total average response times as the sum of the averageaccess delay (that is, the delay from Internet router to institution router) and the average Internet delay. For the average access delay, use △/(1-△β), where △ is the average time required to send an object over the access link and β is the arrival rate of objects to the access link.a. Find the total average response time.b. Now suppose a cache is installed in theinstitutional LAN. Suppose the hit rate is 0.6. Find the total response time.Answer:a.T he time to transmit an object of sizeL over a link or rate R is L/R. The average time is the average size of the object divided by R:Δ= (900,000 bits)/(1,500,000 bits/sec) = 0.6 secThe traffic intensity on the link is (1.5requests/sec)(0.6 sec/request) = 0.9. Thus, the average access delay is (0.6 sec)/(1 - 0.9) = 6 seconds. The total average response time is therefore 6 sec + 2 sec = 8 sec.b.T he traffic intensity on the access linkis reduced by 40% since the 40% of the requests are satisfied within the institutional network. Thus the average access delay is (0.6 sec)/[1 –(0.6)(0.9)] = 1.2 seconds. The responsetime is approximately zero if the request is satisfied by the cache (which happens with probability 0.4); the average response time is 1.2 sec + 2 sec = 3.2 sec for cache misses (which happens 60% of the time). So the average response time is (0.4)(0 sec) +(0.6)(3.2 sec) = 1.92 seconds. Thus theaverage response time is reduced from 8 sec to 1.92 sec.16. (P12) What is the difference betweenMAIL FROM: in SMTP and From: in the mail message itself?Answer: The MAIL FROM: in SMTP is a message from the SMTP client that identifies the sender of the mail message to the SMTP server. The From: on the mail message itself is NOT an SMTP message, but rather is just a line in the body of the mail message.17. (P16) Consider distributing a file of F= 5 Gbits to N peers. The server has an upload rate of u= 20 Mbps, and each peers=1 Mbps and an has a download rate of diupload rate of u. For N = 10, 100, and 1,000 and u = 100 Kbps, 250 Kbps, and 500 Kbps, prepare a chart giving the minimumdistribution time for each of the combinations of N and u for both client-server distribution and P2P distribution.Answer: For calculating the minimum distribution time for client-server distribution, we use the following formula:D cs = max {NF/u s , F/d min }Similarly, for calculating the minimum distribution time for P2P distribution, we use the following formula:D P2P = max{F/u s ,F/d min ,NF/( u s +∑u i n i=1 )}Where,F = 5 Gbits = 5 * 1024 Mbitsu s = 20 Mbpsd min = d i = 1 MbpsClient Server:N10 100 1000200 Kbps 10240 51200 512000u 600 Kbps 10240 51200 512000 1Mbps 10240 51200 512000Peer to Peer:N10 100 1000200 Kbps 10240 25904.3 47559.33 U 600 Kbps 10240 13029.6 16899.641 Mbps 10240 10240 10240。
c语言与程序设计-第2章课后习题参考答案
2.1 下列哪些是词法记号?关键字(是)注释空白符八进制常量(是)三字符序列字符串常量(是)括号(是)2.2 C编译器可将下列每一个源字符串分解为哪些记号?(不必考虑记号组合是否合法)(1)x+++y x, ++, +, y(2)-0xabL -, 0xabL(3) 2.89E+12L 2.89E+12L(4)"String+\"FOO\"" " String+ \"FOO\""(5)x**2 x, *, *, 2(6)"X??/" "X??/"(7)a?b a, ?, b(8)x--+=y x, --, +=, y(9)intx=+10 intx, =, +, 10(10)"String""FOO" "String", "FOO"(这道题当时改的时候有几个小题改得有错误,注意!)2.3 下列哪些不是标识符,为什么?标识符由字母、数字和下划线组成,但首字符必须是字母或下划线。
4th 不是,以数字开头;sizeof 不是(标准C的关键字)_limit 是_is2 是xYshould 是x*y 不是,* 非法o_no_o_no 是temp-2 不是,- 非法isn't 不是,' 非法enum 不是(标准C的关键字。
注:关键字也称为保留字,是被系统赋予特定含义并有专门用途的标识符。
关键字不能作为普通标识符,但可以作为宏名。
所有预处理均发生在识别这些关键字之前。
)2.4 在下列表示中,哪些是合法常数,哪些是非法常数?对于合法常数,指出其类型;对于非法常数,说明其错误原因。
2L 合法,long长整型''' 不合法,单引号组中的单引号前需要转义字符.12 合法,double双精度浮点型0x1ag 不合法,g不是16进制数中的符号,也不表示任何类型33333 合法,int整形"a" 合法,字符串常量"" 合法,字符串常量0.L 合法,long double长双精度浮点型E20 不合法,缺少尾数部分0377UL 合法,unsigned long无符号长整型'\18' 不合法,存在非8进制位'\0xa' 不合法,不符合十六进制字符码表示规则\xhh0x9cfU 合法,unsigned int无符号整形'\45' 合法,char字符型1.E-5 合法,double双精度浮点型'\0' 合法,char字符型3.F 合法,float浮点型"3'4"" 不合法,缺少转义符'"' 合法,char字符型(P35,双引号作为字符常量时既可用图形符号也可用转义序列表示)'\a' 合法,char字符型2.6 以下的变量声明语句中有什么错误?(1)int a; b = 5; 第一个分号改为逗号int a, b=5;(2)doubel h; 关键字错误double h;(3)int x = 2.3; 类型错误float x = 2.3;(4)const long y; 需要赋初值const long y = 0;(5)float a = 2.5*g; g未定义变量int g = 1; float a = 2.5*g;(6)int a = b = 2; b未定义变量int a = 2, b = 2;2.7 设变量说明为:int a = 1, b = 2, c = 3, d;double x = 2.0; y = 7.7;请给出下列表达式的值。
快速入门Scala编程语言
快速入门Scala编程语言Scala编程语言是一种多范式编程语言,结合了面向对象编程和函数式编程的特点。
它的语法简洁优雅,适合用于大规模的软件开发项目。
本文将带你快速了解Scala编程语言。
一、Scala的基本语法1. 变量和常量:在Scala中,使用关键字`var`来声明一个可变的变量,使用关键字`val`来声明一个不可变的常量。
例如,`var x = 10`声明一个可变变量x,`val y = 5`声明一个不可变常量y。
2. 数据类型:Scala拥有丰富的数据类型,包括整数类型、浮点数类型、布尔类型、字符类型等。
例如,`Int`表示整数类型,`Double`表示浮点数类型,`Boolean`表示布尔类型,`Char`表示字符类型。
3. 控制流语句:Scala支持常见的控制流语句,如条件判断和循环。
例如,`if-else`语句用于条件判断,`for`循环用于迭代执行操作。
4. 函数:在Scala中,函数是一等公民,可以作为值进行传递和操作。
函数的定义使用关键字`def`,例如`def add(x: Int, y: Int): Int = x + y`定义了一个接受两个整数参数并返回它们的和的函数。
5. 类和对象:Scala是一种面向对象的语言,每个值都是一个对象。
类用于定义对象的蓝图,对象是类的实例。
通过使用`class`关键字定义类,使用`new`关键字来创建对象。
二、函数式编程特性Scala内置了许多函数式编程特性,使得函数的组合和操作更加简洁和灵活。
1. 高阶函数:Scala中的函数可以作为值进行传递和操作,因此可以使用函数作为参数或返回值。
这种函数接受其他函数作为参数或将函数作为返回值的函数称为高阶函数。
高阶函数可以极大地简化代码的编写和理解。
2. 不可变性:Scala鼓励使用不可变的数据结构和变量,在处理数据时避免副作用和数据竞争的发生。
不可变性使得代码更加安全和易于调试。
3. 模式匹配:模式匹配是一种强大的功能,用于根据数据的结构和属性进行分支处理。
matlab第二章习题答案
第一大题:(1)a = 7/3b = sym(7/3)c = sym(7/3,'d')d = sym('7/3')v1=vpa(abs(a-d))v2=vpa(abs(b-d))v3=vpa(abs(c-d))a =2.3333b =7/3c =2.3333333333333334813630699500209d =7/3v1 =0.0v2 =0.0v3 =0.00000000000000014802973661668756666666667788716(2)a = pi/3b = sym(pi/3)c = sym(pi/3,'d')d = sym('pi/3')v1=vpa(abs(a-d))v2=vpa(abs(b-d))v3=vpa(abs(c-d))a =1.0472b =pi/3c =1.047197551196597631317786181171d =pi/3v1 =0.0v2 =0.0v3 =0.00000000000000011483642827992216762806615818554(3)a = pi*3^(1/3)b = sym(pi*3^(1/3))c = sym(pi*3^(1/3),'d')d = sym('pi*3^(1/3)')v1=vpa(abs(a-d))v2=vpa(abs(b-d))v3=vpa(abs(c-d))a =4.5310b =1275352044764433/281474976710656c =4.5309606547207899041040946030989d =pi*3^(1/3)v1 =0.00000000000000026601114166290944374842393221638 v2 =0.00000000000000026601114166290944374842393221638 v3 =0.0000000000000002660111416629094726767991785515第二大题:(1)c1=3/7+0.1c1 =0.5286双精度(2)c2=sym(3/7+0.1)c2 =37/70符号(3)c3=vpa(sym(3/7+0.1))c3 =0.52857142857142857142857142857143完整显示精度第三大题:(1)findsym(sym('sin(w*t)'),1)ans =w(2)findsym(sym('a*exp(-X)' ) ,1)ans =a(3)findsym(sym('z*exp(j*theta)'),1)ans =z第四大题:A=sym('[a11 a12 a13;a21 a22 a23;a31 a32 a33]')A =[ a11, a12, a13][ a21, a22, a23][ a31, a32, a33]DA=det(A)DA =a11*a22*a33 - a11*a23*a32 - a12*a21*a33 + a12*a23*a31 + a13*a21*a32 - a13*a22*a31w=inv(A)w =[ (a22*a33 - a23*a32)/(a11*a22*a33 - a11*a23*a32 - a12*a21*a33 +a12*a23*a31 + a13*a21*a32 - a13*a22*a31), -(a12*a33 -a13*a32)/(a11*a22*a33 - a11*a23*a32 - a12*a21*a33 + a12*a23*a31 +a13*a21*a32 - a13*a22*a31), (a12*a23 - a13*a22)/(a11*a22*a33 -a11*a23*a32 - a12*a21*a33 + a12*a23*a31 + a13*a21*a32 - a13*a22*a31)] [ -(a21*a33 - a23*a31)/(a11*a22*a33 - a11*a23*a32 - a12*a21*a33 +a12*a23*a31 + a13*a21*a32 - a13*a22*a31), (a11*a33 -a13*a31)/(a11*a22*a33 - a11*a23*a32 - a12*a21*a33 + a12*a23*a31 +a13*a21*a32 - a13*a22*a31), -(a11*a23 - a13*a21)/(a11*a22*a33 -a11*a23*a32 - a12*a21*a33 + a12*a23*a31 + a13*a21*a32 - a13*a22*a31)] [ (a21*a32 - a22*a31)/(a11*a22*a33 - a11*a23*a32 - a12*a21*a33 +a12*a23*a31 + a13*a21*a32 - a13*a22*a31), -(a11*a32 -a12*a31)/(a11*a22*a33 - a11*a23*a32 - a12*a21*a33 + a12*a23*a31 +a13*a21*a32 - a13*a22*a31), (a11*a22 - a12*a21)/(a11*a22*a33 -a11*a23*a32 - a12*a21*a33 + a12*a23*a31 + a13*a21*a32 - a13*a22*a31)] IAs=subexpr(w,'d')d =1/(a11*a22*a33 - a11*a23*a32 - a12*a21*a33 + a12*a23*a31 + a13*a21*a32 - a13*a22*a31)IAs =[ d*(a22*a33 - a23*a32), -d*(a12*a33 - a13*a32), d*(a12*a23 -a13*a22)][ -d*(a21*a33 - a23*a31), d*(a11*a33 - a13*a31), -d*(a11*a23 -a13*a21)][ d*(a21*a32 - a22*a31), -d*(a11*a32 - a12*a31), d*(a11*a22 -a12*a21)]第六大题:syms ksyms x positives_s=2/(2*k+1)*((x-1)/(x+1))^(2*k+1)s_ss=simple(symsum(s_s,k,0,inf))s_s =(2*((x - 1)/(x + 1))^(2*k + 1))/(2*k + 1)警告: simple will be removed in a future release. Use simplify instead. [> In sym.simple at 41]s_ss =log(x)第八大题:syms x clearsyms xh=exp(-abs(x))*abs(sin(x))si=vpa(int(h,-5*pi,1.7*pi),64)h =abs(sin(x))*exp(-abs(x))si =1.087849417255503701102633764498941389696991336803454392428439159 第九大题:syms x y clearsyms x yr=int(int(x^2+y^2,y,1,x^2),x,1,2)r =1006/105第十大题:syms t x;f=sin(t)/t;y=int(f,t,0,x)y1=subs(y,x,sym('4.5'))ezplot(y,[0,2*pi])y =sinint(x)y1 =syms x clearsyms x ny=sin(x)^nyn=int(y,0,1/2*pi)y31=vpa(subs(yn,n,sym('1/3')))y32=vpa(subs(yn,n,1/3))y =sin(x)^nyn =piecewise([-1 < real(n), beta(1/2, n/2 + 1/2)/2], [real(n) <= -1, int(x^n/(1 - x^2)^(1/2), x, 0, 1)])y31 =1.2935547796148952674767575125656y32 =1.2935547796148952674767575125656第二十题:clearsyms y xy=dsolve('(Dy*y)/5+x/4=0','x')y =2^(1/2)*(C6 - (5*x^2)/8)^(1/2)-2^(1/2)*(C6 - (5*x^2)/8)^(1/2)y1=subs(y,'C6',1)y1 =2^(1/2)*(1 - (5*x^2)/8)^(1/2)-2^(1/2)*(1 - (5*x^2)/8)^(1/2)clfhy1=ezplot(y1(1),[-2,2,-2,2],1)set(hy1,'Color','r')grid onhold onhy2=ezplot(y1(2),[-2,2,-2,2],1)set(hy2,'Color','b')grid onxlabel('Y')ylabel('X')hold offbox onlegend('y(1)','y(2)','Location','Best')hy1 =174.0155hy2 =177.0145。
DS第二章_课后习题答案
第二章线性表2、1 填空题(1)一半插入或删除得位置(2)静态动态(3)一定不一定(4)头指针头结点得next 前一个元素得next2、2 选择题(1)A (2) DA GKHDA EL IAF IFA(IDA)(3)D (4)D (5) D2、3头指针:在带头结点得链表中,头指针存储头结点得地址;在不带头结点得链表中,头指针存放第一个元素结点得地址;头结点:为了操作方便,在第一个元素结点前申请一个结点,其指针域存放第一个元素结点得地址,数据域可以什么都不放;首元素结点:第一个元素得结点。
2、4已知顺序表L递增有序,写一算法,将X插入到线性表得适当位置上,以保持线性表得有序性。
void InserList(SeqList *L,ElemType x){int i=L->last;if(L->last>=MAXSIZE-1) return FALSE; //顺序表已满while(i>=0 && L->elem[i]>x){L->elem[i+1]=L->elem[i];i--;}L->elem[i+1]=x;L->last++;}2、5 删除顺序表中从i开始得k个元素int DelList(SeqList *L,int i,int k){int j,l;if(i<=0||i>L->last) {printf("The Initial Position is Error!"); return 0;}if(k<=0) return 1; /*No Need to Delete*/if(i+k-2>=L->last) L->last=L->last-k; /*modify the length*/for(j=i-1,l=i+k-1;l<L->last;j++,l++)L->elem[j]=L->elem[l];L->last=L->last-k;return 1;}2、6 已知长度为n得线性表A采用顺序存储结构,请写一时间复杂度为O(n)、空间复杂度为O(1)得算法,删除线性表中所有值为item得数据元素。
[VIP专享]面向对象程序设计第二章课后答案
1.什么是命名空间,如何访问命名空间的成员?【解答】为了解决不同文件中同名变量的问题,C++标准中引入命名空间的概念。
命名空间(namespace)是一种特殊的作用域,命名空间可以由程序员自己来创建,可以将不同的标识符集合在一个命名作用域内,这些标识符可以类、对象、函数、变量、结构体、模板以及其他命名空间等。
在作用域范围内使用命名空间就可以访问命名空间定义的标识符。
有3种访问方法:(1)直接指定标识符,访问方式为:命名空间标识符名∷成员名。
(2)使用using namespace命令(3)使用using关键词声明2.什么是内联函数,它有什么特点?哪些函数不能定义为内联函数?【解答】用inline关键字声明或定义的函数称为内联函数。
C++中对于功能简单、规模小、使用频繁的函数,可以将其设置为内联函数。
内联函数(inline function)的定义和普通函数相同,但C++对它们的处理方式不一样。
在编译时,C++将用内联函数程序代码替换对它每次的调用。
这样,内联函数没有函数调用的开销,即节省参数传递、控制转移的开销,从而提高了程序运行时的效率。
但是,由于每次调用内联函数时,需要将这个内联函数的所有代码复制到调用函数中,所以会增加程序的代码量,占用更多的存储空间,增大了系统空间方面的开销。
因此,内联函数是一种空间换时间的方案。
函数体内有循环语句和switch语句,递归调用的函数不能定义为内联函数。
3.什么是函数重载?在函数调用时,C++是如何匹配重载函数的?【解答】函数重载是指两个或两个以上的函数具有相同的函数名,但参数类型不一致或参数个数不同。
编译时编译器将根据实参和形参的类型及个数进行相应地匹配,自动确定调用哪一个函数。
使得重载的函数虽然函数名相同,但功能却不完全相同。
在函数调用时,C++是匹配重载函数规则如下:首先寻找一个精确匹配,如果能找到,调用该函数;其次进行提升匹配,通过内部类型转换(窄类型到宽类型的转换)寻求一个匹配,如char到int、short到int等,如果能找到,调用该函数;最后通过强制类型转换寻求一个匹配,如果能找到,调用该函数。
《Spark编程基础及项目实践》课后习题及答案2
第二章习题答案实训代码完整程序如下:文件studentinfo.txt的内容如图1所示,注意在Windows平台下将studentinfo.txt保存为UTF-8的格式。
图1 学生信息在Linux的/usr/local/project目录下创建文件studentinfo.txt,使用命令“touch studentinfo.txt”。
执行命令“vim studentinfo.txt”对文件进行编辑,按“i”进入编辑模式,输入图2-40所示内容,按“Esc”退出编辑状态,再执行命令“:wq”进行保存并退出。
在/usr/local/project目录下创建文件StudentInfo.scala,输入内容如下:import scala.io._import util.control.Breaks._object StudentInfo {var arrInfo:Array[String] = nulldef main(args: Array[String]) {//将/usr/local/project/studentinfo.txt的文件内容读入到数组中//一行为一个元素val lines = for(line <-Source.fromFile("/usr/local/project/studentinfo.txt").getLines) yield linearrInfo = lines.toArrayvar flag = trueshow()while(flag){print("请输入选择序号:")val choice = StdIn.readLine()breakable{if(!isIntByRegex(choice)) {//如果输入不是数字,则跳出本次循环println("请输入正确的序号")break}choice.toInt match {case 1 => {var maleCnt = count("男")println("三个班级共有男生" + maleCnt +"人")}case 2 => {var femalCnt = count("女")println("三个班级共有女生" + femalCnt +"人")}case 3 => {print("输入学号:")val studentId = StdIn.readLine()var mark = falsebreakable{for(i <- 0 until arrInfo.length){var info = arrInfo(i)val arr : Array[String] = info.split("\t")if(arr(1)== studentId){mark = trueprintln("班级\t学号\t姓名\t性别\t年龄\t籍贯\t电话")println(info)break //找到了学号,就跳出breakable,终止循环}}}if(!mark){println("查无此人")}}case 4 => {//按班级进行分组print("输入班级序号:")val classId = StdIn.readLine()println("班级\t学号\t姓名\t性别\t年龄\t籍贯\t电话")/*** 将arrInfo数组使用groupBy函数按照班级序号进行分组* 先将数组中的每个元素按照"\t"进行分割* 提取出分割后的第一个元素(即班级序号)* 按照班级序号进行分组,返回一个Map[String,Array[String]]类型 * 将返回值赋值给mapArr*/val mapArr = arrInfo.groupBy(x => x.split("\t")(0))for(maparr <- mapArr(classId)) println(maparr)}case 5 => {flag = falseprintln("再见!")}case _ => println("输入错误,请重新输入")}}}}//使用正则表达式判断字符串s是否为数字def isIntByRegex(s : String) = {val pattern = """^(\d+)$""".rs match {case pattern(_*) => truecase _ => false}}//展示功能页面def show() = {println("**************************************") println("1. 统计男生人数")println("2. 统计女生人数")println("3. 输入学号,打印出学生信息")println("4. 输入班级序号,打印出班级学生信息列表")println("5. 退出")println("**************************************") }//根据指定的信息统计人数def count(param: String): Int = {var sum = 0for(info <- arrInfo; if info.contains(param)){sum += 1}sum}}运行结果如图2-50所示。
面向对象程序设计第二章课后答案说课讲解
面向对象程序设计第二章课后答案1.什么是命名空间,如何访问命名空间的成员?【解答】为了解决不同文件中同名变量的问题,C++标准中引入命名空间的概念。
命名空间(namespace)是一种特殊的作用域,命名空间可以由程序员自己来创建,可以将不同的标识符集合在一个命名作用域内,这些标识符可以类、对象、函数、变量、结构体、模板以及其他命名空间等。
在作用域范围内使用命名空间就可以访问命名空间定义的标识符。
有3种访问方法:(1)直接指定标识符,访问方式为:命名空间标识符名∷成员名。
(2)使用using namespace命令(3)使用using关键词声明2.什么是内联函数,它有什么特点?哪些函数不能定义为内联函数?【解答】用inline关键字声明或定义的函数称为内联函数。
C++中对于功能简单、规模小、使用频繁的函数,可以将其设置为内联函数。
内联函数(inline function)的定义和普通函数相同,但C++对它们的处理方式不一样。
在编译时,C++将用内联函数程序代码替换对它每次的调用。
这样,内联函数没有函数调用的开销,即节省参数传递、控制转移的开销,从而提高了程序运行时的效率。
但是,由于每次调用内联函数时,需要将这个内联函数的所有代码复制到调用函数中,所以会增加程序的代码量,占用更多的存储空间,增大了系统空间方面的开销。
因此,内联函数是一种空间换时间的方案。
函数体内有循环语句和switch语句,递归调用的函数不能定义为内联函数。
3.什么是函数重载?在函数调用时,C++是如何匹配重载函数的?【解答】函数重载是指两个或两个以上的函数具有相同的函数名,但参数类型不一致或参数个数不同。
编译时编译器将根据实参和形参的类型及个数进行相应地匹配,自动确定调用哪一个函数。
使得重载的函数虽然函数名相同,但功能却不完全相同。
在函数调用时,C++是匹配重载函数规则如下:首先寻找一个精确匹配,如果能找到,调用该函数;其次进行提升匹配,通过内部类型转换(窄类型到宽类型的转换)寻求一个匹配,如char到int、short到int等,如果能找到,调用该函数;最后通过强制类型转换寻求一个匹配,如果能找到,调用该函数。
快学Scala习题解答—第三章数组相关操作
快学Scala习题解答—第三章数组相关操作3 数组相关操作3.1 编写⼀段代码。
将a设置为⼀个n个随机整数的数组,要求随机数介于0(包括)和n(不包括)之间random和yield的使⽤Scala代码1. import scala.math.random2.3. def randomArray(n:Int)={4. for(i <- 0 until n) yield (random * n).toInt5. }6.7. println(randomArray(10).mkString(","))3.2 编写⼀个循环,将整数数组中相邻的元素置换。
⽐如,Array(1,2,3,4,5)经过置换后变为Array(2,1,4,3,5)对数组⽅法的使⽤Scala代码1. def reorderArray(arr:Array[Int]):Array[Int]={2. val t = arr.toBuffer3. for(i <- 1 until (t.length,2);tmp = t(i);j <- i - 1 until i){4. t(i) = t(j)5. t(j) = tmp6. }7. t.toArray8. }9.10. println(reorderArray(Array(1,2,3,4,5)).mkString(","))3.3 反复前⼀个练习,只是这⼀次⽣成⼀个新的值交换过的数组。
⽤for/yieldScala代码1. def reorderArray(arr:Array[Int]):Array[Int]={2. (for(i <- 0 until (arr.length,2)) yield if (i + 1 < arr.length) Array(arr(i + 1),arr(i)) else Array(arr(i))).flatten.toArray3. }4.5. println(reorderArray(Array(1,2,3,4,5)).mkString(","))3.4 给定⼀个整数数组,产⽣⼀个新的数组,包括元数组中的全部正值,以原有顺序排列,之后的元素是全部零或负值。
scala课后习题答案
scala课后习题答案Scala课后习题答案Scala是一种多范式编程语言,它结合了面向对象编程和函数式编程的特性。
在学习Scala的过程中,做课后习题是非常重要的,它可以帮助我们巩固所学的知识,提高编程能力。
下面我们来看一些常见的Scala课后习题及其答案。
1. 编写一个函数,计算给定数组的平均值。
```scaladef average(arr: Array[Int]): Double = {if (arr.isEmpty) 0else arr.sum.toDouble / arr.length}```2. 编写一个函数,将给定的字符串列表连接成一个字符串。
```scaladef concatStrings(strings: List[String]): String = {strings.mkString}```3. 编写一个函数,找出给定数组中的最大值和最小值。
```scaladef findMaxAndMin(arr: Array[Int]): (Int, Int) = {(arr.max, arr.min)}```4. 编写一个函数,将给定的整数列表按照奇偶分成两个列表。
```scaladef splitOddEven(nums: List[Int]): (List[Int], List[Int]) = {nums.partition(_ % 2 == 0)}```5. 编写一个递归函数,计算给定数字的阶乘。
```scaladef factorial(n: Int): Int = {if (n <= 1) 1else n * factorial(n - 1)}```以上是一些常见的Scala课后习题及其答案,通过做这些习题可以帮助我们更好地理解和掌握Scala编程语言。
希望大家在学习Scala的过程中能够多加练习,不断提升自己的编程能力。
【第二章】算法竞赛入门经典(第二版)-课后习题答案
2-1 Daffodil2017年10月1日12:561 #include<stdio.h>2 int main(void)3 {4 int shui,xian,hua;5 int n =100;6 int g,s,b;7 int sum =0;8 while(n <1000)9 {10 g =n%10;11 s =n/10%10;12 b =n/100;13 shui =g*g*g;14 xian =s*s*s;15 hua =b*b*b;16 sum =shui +xian +hua;17 if(sum ==n)printf("%d\n",n);18 n++;19 }20 return0;21 }2-2 Hanxin2017年10月1日12:591 #include<stdio.h>2 int main(void)3 {4 int s,w,q;5 int kase =0;6 while(scanf("%d%d%d", &s, &w, &q) !=EOF)7 {8 int i =0;9 int n =10;10 while(n <=101)11 {12 if(n%3==s &&n%5==w &&n%7==q &&n <=100)13 {14 printf("Case %d: %d\n", ++kase,n);15 i =1;16 }17 else if(n >100&&i ==0)printf("Case %d: No answer\n", ++kase);18 n++;19 }20 }21 return0;22 }2-3 Triangle2017年10月1日12:591 #include <stdio.h>2 int main()3 {4 int i, j, n;5 scanf("%d", &n);6 for(i = 0; i < n; i++)7 {8 for(j= 0; j< I; j++)9 printf(" ");10 for(j= 0; j< 2*(n-i)-1; j++)11 printf("#\n");12 }13return0;14}2-4 Subsequence2017年10月1日13:001 #include<stdio.h>2 int main(void)3 {4 long long n,m;5 int kase =0;6 for( ; ; )7 {8 scanf("%lld%lld", &n, &m);9 if(n ==0&&m ==0)break;10 double sum =0.0;11 while(n <=m)12 {13 long long a =n*n;14 double b = (double)1.0/a;15 sum +=b;16 n++;17 }18 printf("Case %d: %.5lf\n", ++kase,sum);19 }20 return0;21 }22 /*23 将所有int改为long long方才解决问题,为什么?24 long long n, m; 为什么不能为int n, m; ?25 */2-5 Decimal2017年10月1日13:001 #include<stdio.h>2 int main(void)3 {4 int a,b,c;5 int kase =0;6 int i;7 for(;;)8 {9 scanf("%d%d%d", &a, &b, &c);10 if(a ==0&&b ==0&&c ==0)break;11 a %=b;12 printf("Case %d: %d.", ++kase,a/b);13 for(i =1;i <c;i++)14 {15 printf("%d",a*10/b);16 a =a*10%b;17 }18 if(a%b*10*10/b >=5)19 printf("%d\n",a%b*10/b+1);20 else21 printf("%d\n",a%b*10/b);22 }23 return0;24 }25 /*26 循环+判断 可以避开数组...27 求余的式子很巧妙...28 */2-6 Permutation2017年10月1日13:001 #include<stdio.h>2 int main(void)3 {4 int a,b,c,d,e,f,g,h,i;5 int n =100;6 while(n <=333)7 {8 a =n/100;9 b =n/10%10;10 c =n%10;11 if(a ==b ||a ==c ||b ==c )12 n++;13 else if(b ==0||c ==0)14 n++;15 else16 {17 int n2 =n*2;18 d =n2/100;19 e =n2/10%10;20 f =n2%10;21 if(e ==0||f ==0)22 n++;23 else if(d ==e ||d ==f ||e ==f)24 n++;25 else if(d ==b ||d ==c)// d == a省略,百位不会相等26 n++;27 else if(e ==a ||e ==b ||e ==c)28 n++;29 else if(f ==a ||f ==b ||f ==c)30 n++;31 else32 {33 int n3 =n*3;34 g =n3/100;35 h =n3/10%10;36 i =n3%10;37 if(h ==0||i ==0)38 n++;39 else if(g ==h ||g ==i ||h ==i)40 n++;41 else if(g ==b ||g ==c ||g ==e ||g ==f)42 n++;43 else if(h ==a ||h ==b ||h ==c ||h ==d ||h ==e ||h ==f)43 else if(h ==a ||h ==b ||h ==c ||h ==d ||h ==e ||h ==f)44 n++;45 else if(i ==a ||i ==b ||i ==c ||i ==d ||i ==e ||i ==f)46 n++;47 else48 {49 printf("%d %d %d\n",n,n2,n3);50 n++;51 }52 }53 }54 }55 return0;56 }Chapter 2 Q&A2017年10月1日13:001 #include<stdio.h>2 int main(void)3 {4 int n,i;5 scanf("%d", &n);6 for(i =1;i <=n;i++)7 printf("%d\n",i);89 /*10 for(i = 1; i <= n; i++)11 printf("%d\n", 2*i); //任务一1213 for(i = 2; i <= 2*n; i+=2) //任务二14 printf("%d\n", i);15 */1617 return0;18 }1 #include<stdio.h>2 int main(void)3 {4 double i;5 for(i =0;i !=10;i +=0.1)6 printf("%.1f\n",i);7 return0;8 }。
快学scala第四章习题答案
abstract def zip[B](that: GenIterable[B]): StringOps[(A, B)]
GenIterable是可遍历对象需要包含的trait,对于String来说,它是可遍历的。但是它的遍历是遍历单个字母。所以拉链就针对每个字母来进行。
(values.count(_ < v),values.count(_ == v),values.count(_ > v))
}
5.10当你将两个字符串拉链在一起,比如"Hello".zip("World"),会是什么结果?想出一个讲得通的用例
scala> "Hello".zip("World")
res0: scala.collection.immutable.IndexedSeq[(Char, Char)] = Vector((H,W), (e,o), (l,r), (l,l), (o,d))
当然使用Scala的方法啦。参考第9章
首先,创建一个文件myfile.txt。输入如下内容
test test ttt test ttt t test sss s
Scala代码如下
importscala.io.Source
importscala.collection.mutable.HashMap
//val source = Source.fromFile("myfile.txt")
5.5重复前一个练习,这次使用java.util.TreeMap并使之适用于Scala API
主要涉及java与scala的转换类的使用
importscala.io.Source
快学scala第二章习题答案
2 控制结构和函数
2.1 一个数字如果为正数,则它的signum为1;如果是负数,则signum 为-1;如果为0,则signum为0.编写一个函数来计算这个值简单的逻辑判断
可以看出,它的值是()类型是Unit
2.2 指出在Scala中何种情况下赋值语句x=y=1是合法的。
(提示:给x找个合适的类型定义)
题目已经给了明确的提示了。
本章节中已经说过了,在scala中的赋值语句是Unit类型。
所以只要x为Unit类型就可以了。
这也再次证明了{}是Unit类型
2.4 针对下列Java循环编写一个Scala版本:for(int
i=10;i>=0;i–)System.out.println(i);
使用Scala版本改写就OK了
2.6 编写一个for循环,计算字符串中所有字母的Unicode代码的乘积。
举例来说,"Hello"中所有字符串的乘积为9415087488L
2.10 编写函数计算x n,其中n是整数,使用如下的递归定义:
∙x n=y2,如果n是正偶数的话,这里的y=x(n/2)∙x n = x*x(n-1),如果n是正奇数的话
∙x0 = 1
∙x n = 1/x(-n),如果n是负数的话。
编译原理第二章习题答案
* i
=> 〈表达式〉
〈运算符〉
i * i
=>〈表达式〉+i * i
=>1+1*1
所以,该文法是二义的。
9.文法G⑸为:
S->Ac|aB
A->ab
B->bc
该文法是否为பைடு நூலகம்义的为什么
[答案]
对于串abc
(l)S=>Ac=>abc
⑵S=>aB=>abc
即存在两不同的最右推导
所以,该文法是二义的。
最右推导:
S=>ABS=>ABAa=>ABaa=>ASBBaa=>ASBbaa=>ASbbaa=>A £ bbaa=>a £ bbaa
(2)产生式有:S-ABS |Aa|£
A~*a
B—SBB|b
(3)该句子的短语有8ibib2a283、ai、bi> b2、bib2、82^3、a2;
!
直接短语有ai、bi、b2、a2:
4•已知文法G[Z]:
Z->aZb|ab
<
写出L(G[Z])的全部元素。
[答案]
Z=>aZb=>aaZbb=>aaa..Z...bbb=> aaa..ab...bbb
L(G[Z])={anbn|n>=l}
5.给出语言{aBc叫n>=l,m>=O}|ft上下文无关文法。
[分析]
本题难度不大,主要是考上下文无关文法的基本概念。上下文无关文法的基 本定义是:A->P,AeVn, P G (VnUVt)\注意关键问题是保证a"bn的成立, 即“a与b的个数要相等”,为此,可以用一条形如A->aAb|ab的产生式即可解 决。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
2 控制结构和函数
2.1 一个数字如果为正数,则它的signum为1;如果是负数,则signum 为-1;如果为0,则signum为0.编写一个函数来计算这个值简单的逻辑判断
可以看出,它的值是()类型是Unit
2.2 指出在Scala中何种情况下赋值语句x=y=1是合法的。
(提示:给x找个合适的类型定义)
题目已经给了明确的提示了。
本章节中已经说过了,在scala中的赋值语句是Unit类型。
所以只要x为Unit类型就可以了。
这也再次证明了{}是Unit类型
2.4 针对下列Java循环编写一个Scala版本:for(int
i=10;i>=0;i–)System.out.println(i);
使用Scala版本改写就OK了
2.6 编写一个for循环,计算字符串中所有字母的Unicode代码的乘积。
举例来说,"Hello"中所有字符串的乘积为9415087488L
2.10 编写函数计算x n,其中n是整数,使用如下的递归定义:
∙x n=y2,如果n是正偶数的话,这里的y=x(n/2)∙x n = x*x(n-1),如果n是正奇数的话
∙x0 = 1
∙x n = 1/x(-n),如果n是负数的话。