programming in ANSI C-Chapter 4 Managing input and output operations
java四大名著

1. 《Java编程思想(第4版)》基本信息原书名:Thinking in Java (4th Edition)原出版社:Prentice Hall PTR作者:(美)Bruce Eckel [作译者介绍]译者:陈昊鹏丛书名:计算机科学丛书出版社:机械工业出版社ISBN:9787111213826上架时间:2007-6-19出版日期:2007年6月推荐语本书是全球程序员必备图书《Java编程思想》的最新版本(《Java编程思想(英文影印版.第4版)》)本书曾获:·被china-pub会员评为“2007年我最喜爱的十大技术图书”之一·2003年《Software Development》杂志最佳书籍Jolt大奖·2003年《Java Developer’s Journal》读者选择最佳书籍奖·2001年《Java World》编辑选择最佳书籍奖·2000年《Java World》读者选择最佳书籍奖·1999年《Software Development》杂志最佳产品奖·1998年《Java Developer’s Journal》编辑选择最佳书籍奖内容简介本书赢得了全球程序员的广泛赞誉,即使是最晦涩的概念,在bruce eckel的文字亲和力和小而直接的编程示例面前也会化解于无形。
从java的基础语法到最高级特性(深入的面向对象概念、多线程、自动项目构建、单元测试和调试等),本书都能逐步指导你轻松掌握。
从本书获得的各项大奖以及来自世界各地的读者评论中,不难看出这是一本经典之作。
本书的作者拥有多年教学经验,对c、c++以及java语言都有独到、深入的见解,以通俗易懂及小而直接的示例解释了一个个晦涩抽象的概念。
本书共22章,包括操作符、控制执行流程、访问权限控制、复用类、多态、接口、通过异常处理错误、字符串、泛型、数组、容器深入研究、java i/o系统、枚举类型、并发以及图形化用户界面等内容。
编译原理第四版课后答案

编译原理第四版课后答案1. What are the three basic phases of a compiler and what are their main functions?- The three basic phases of a compiler are lexical analysis, syntax analysis, and code generation.- The main function of lexical analysis is to read the source code and break it into individual tokens, such as keywords, identifiers, numbers, and symbols.- The main function of the syntax analysis is to parse the tokens and verify that they form valid syntax according to the grammar rules of the programming language.- The main function of code generation is to convert the parsed tokens into executable code in a target programming language or machine code.2. What is lexical analysis and what are its main tasks?- Lexical analysis is the first phase of a compiler, which reads the source code and breaks it into individual tokens.- The main tasks of lexical analysis include tokenization, where the source code is divided into meaningful units called tokens, such as keywords, identifiers, numbers, and symbols; removal of comments, where any comments in the source code are ignored; and removal of white spaces, where unnecessary spaces, tabs, and line breaks are eliminated.3. What is a parser and what is its main function?- A parser is a component of the compiler that performs syntax analysis, also known as parsing.- Its main function is to analyze the structure of the tokens generated by the lexical analysis phase and verify that they form avalid syntax according to the grammar rules of the programming language.- The parser constructs a derivation tree or a parse tree to represent the structure of the code and checks for syntax errors, such as missing or misplaced tokens.4. What is the difference between a compiler and an interpreter?- A compiler is a program that translates the entire source code of a programming language into an equivalent target code or machine code before execution.- An interpreter, on the other hand, does not translate the entire source code into machine code before execution. Instead, it reads and executes the source code line by line, translating and executing each line as it encounters it.- In terms of efficiency, a compiled program tends to run faster than an interpreted program because the compiled code is already in machine language, whereas the interpreted code needs to be translated and executed at runtime.5. What are the advantages and disadvantages of using an interpreted language?- Advantages of using an interpreted language include faster development time, as there is no need to compile the entire code before execution; easier debugging, as errors can be detected and fixed immediately; and platform independence, as the interpreter can run on different operating systems without the need to compile separate binaries.- Disadvantages of using an interpreted language include slower execution speed compared to compiled languages; lower performance, as the interpreter needs to translate and execute eachline at runtime; and potential security risks, as the interpreted code can be easily accessed and modified.6. What is meant by bytecode and what is its role in interpreter-based execution?- Bytecode is a low-level representation of the source code that is generated by a compiler or an interpreter. It is a set of instructions that can be executed by a virtual machine.- In interpreter-based execution, the source code is first compiled into bytecode, which is a platform-independent representation of the code. The interpreter then reads and executes the bytecode on the virtual machine, providing a compromise between compilation and interpretation.- Bytecode allows for faster execution compared to interpreting the source code directly, as the bytecode is already in a form that can be executed by the virtual machine.7. What is code optimization and why is it important?- Code optimization is the process of improving the efficiency and performance of the generated code by the compiler.- It is important because optimized code can run faster and consume less memory, resulting in improved overall performance of the program.- Code optimization techniques include constant folding, loop unrolling, dead code elimination, and register allocation, among others.8. What is a symbol table and what is its purpose?- A symbol table is a data structure that is used by a compiler to store information about the variable and function namesencountered in the source code.- Its purpose is to keep track of the properties and attributes of each symbol, such as its data type, memory location, scope, and visibility.- The symbol table is used by various phases of the compiler, such as the lexical analyzer, parser, and code generator, to perform tasks such as name resolution, type checking, and memory management.9. What is the role of an assembler in the compilation process?- An assembler is a program that converts assembly language code into machine code.- In the compilation process, the assembler is responsible for translating the assembly language code written by the programmer into machine code that can be executed directly by the computer hardware.- The assembler performs a one-to-one mapping of assembly instructions to their corresponding machine code instructions, and also resolves symbolic addresses and labels used by the programmer.10. What is the difference between a single-pass compiler and a multi-pass compiler?- A single-pass compiler is a compiler that reads the source code of a program once and generates the corresponding executable code in a single pass or iteration.- A multi-pass compiler, on the other hand, requires multiple passes or iterations over the source code in order to generate the executable code.- Single-pass compilers are generally simpler and require less memory, but they are unable to perform certain optimizations orglobal analysis that requires information from the entire source code. Multi-pass compilers are more powerful and can perform more complex optimizations and analysis, but they are typically slower and require more memory.。
C语言程序设计(第4版)英文版

作者简介
Stephen G. Kochan撰写及合作撰写了六本经典的程序设计与Unix书籍,包括Unix Shell Programming和 Programming in Objective-C。他曾任AT&T贝尔实验室的软件顾问,从事Unix和C程序设计的开发与授课工作。
媒体评论
对于任何开始学习使用C语言编写程序的人来说,这本书都是极好的。这是一本优秀的入门教科书,拥有丰富 的示例、出色的文字……我就是用这本书来学习C语言的——这是一本超棒的书。
——Vinit S. Carpenter,Learn C/C++ Today
谢谢观看
本书通过示例来教授C语言,每个新概念都有完整的C程序做演示。Stephen Kochan逐步解释了所有C函数。 你不仅可以学习这门语言的基础知识,还能养成良好的程序设计习惯。每章最后的习题使本书非常适于课堂学习 或自学。
本书涵盖了C语言的所有特性,包括C11标准中新增的内容。附录中详尽总结了C语言和C语言库,两者的组织 形式都便于快速参考。
目录
Introduction 1 Some Fundamentals Programming Higher-Level Languages Operating Systems Compiling Programs Integrated Development Environments Language Interpreters 2 Compiling and Running Your First Program Compiling Your Program Running Your Program
C语言程序设计(第4版)英文版
电子工业出版社出版的图书
01 内容简介
AFirstBookofANSIC,4thEdition第一本书的ANSIC,第四版

A First Book of ANSI C, 4th Edition14188-35560Chapter 1 SolutionsExercises 1.1Short Answer Questions1. A bit is the smallest and most basic data item which is a switch that can be eitheropened or closed. A bit can represent the values 0 and 1.2. A byte is a grouping of eight bits. A byte can assume 256 distinct patterns.3. A byte uses a pattern of eight bits, such as 00110011, to represent characters in acomputer.4. A word is a single unit combination of one or more bytes. Word sizes for somecommon computers include: a single byte for early personal computers, such as the Apple IIe and Commodore machines; two bytes for the first IBM PCs; four bytes forthe more current Intel-based PCs.5. The two principal parts of the CPU are the Control Unit and the Arithmetic and LogicUnit (ALU). The Control Unit monitors the overall operation of the computer while the ALU performs all the arithmetic and logic functions provided by the system.6. The main difference between RAM and ROM is RAM is volatile while ROM isnonvolatile. Both RAM and ROM are random access which means that every section of memory can be accessed randomly as quickly as any other section.7. a. The input/output unit is the interface that provides access to and from thecomputer to which peripheral devices are attached.b. Three devices that would be connected to the input/output unit includekeyboards, monitors and printers. (Please note there are other examples the student could include.)8. Secondary storage is a permanent storage area for programs and data. Threeexamples of secondary storage include magnetic tapes, magnetic disks and CD-ROMS. (Please note there are other examples the student could include.)9. The difference between sequential storage and direct access storage is sequentialstorage allows data to be written or read in one sequential stream from beginning to end while direct access storages allows data to be written or read from any one fileor program independent of its position on the storage medium. Direct access storageallows the computer to jump directly to the desired point in storage, rather thanpassing through all intervening points like sequential storage would require. In other words, the data can be accessed more quickly.10. A microprocessor is a single microchip CPU. In everyday life microprocessors areused in notebook and desktop computers, calculators, and even digital watches.(Please note there are other examples the student could include.)Exercises 1.21. a. computer program -a self-c ontained set of in struct ions and data used to operatea computer to produce a specific resultb. programming -the process of developing and writing a programc. programming language-the set of data and instructions that can be used toconstruct a programd. high-level language-languages in which the instructions resemble humanlanguages, such as English, and can be run on a variety of computer typese. low-level language-language that uses instructions that are directly tied to onetype of computerf. machine language-a programming language consisting of the binary codes thecan be executed by a computerg. assembly language-a programming language that uses symbolic names foroperations and memory addressesh. procedure-oriented language-high-level language in which the instructions areonly used to create self-contained units referred to as proceduresi. object-oriented language-high-level language which defines and manipulatesobjects to produce resultsj. source program-program written in a computer languagek. compiler -program which translates high-level languages as a complete unitbefore any individual statement is executedl. assembler-a program that converts, or translates, assembly language programs into machine language2. a. A high-level language can be translated to run on a variety of computer types,while a low-level language is directly tied to one type of computer.b. Procedure-oriented languages create logically consistent sets of instructions, orprocedures, to produce a specific result while object-oriented languages create and manipulate objects to produce specific results.3. An assembler translates assembly language programs, while both compilers andinterpreters translate high-level source programs. A compiler translates a high- level source programs as a complete unit before any one statement is actually executed,while an interpreter translates individual source program statements one at a time into executable statements. Each interpreted statement is executed immediatelyafter translation.4. a. Add the data in memory location 1 to the data in memory location 2. Multiply thedata in memory location 3 by the data in memory location 2. Subtract the data inmemory location 4 from the data in memory location 3. Divide the data in memory location 3 by the data in memory location 5.b. 3 + 5 = 86 * 3 = 186 -14 = -86 / 4 = 1.55. ADD 1, 2MUL 3, 2SUB 4, 3DIV 3, 56. (10 + 20) * .6 = 18Exercises 1.31. a. Fix a flat tireStop vehicle in a safe, level locationSet the parking brakeGet jack, lug-wrench, and spare tireCheck air pressure in spare tireUse jack to raise vehicle so that damaged tire is clear of groundRemove hubcapUse lug-wrench to loosen each individual lug nutUse lug-wrench to remove each individual lug nutPlace lug nuts into hubcapRemove tire from axlePlace spare tire onto axleRestore each lug nut, and tighten by handTighten all lug nuts securely with lug-wrenchReplace hubcapRelease jackReturn jack, lug-wrench, and damaged tire to trunk of vehicleb. Make a telephone callLift telephone receiverDial a numberWait for answerSpeak to person, or respond to electronic instructionsc. Go to the store and purchase a loaf of breadTransport yourself to the storeFind bakery departmentSelect an appropriate loaf of breadProceed to checkout areaExchange money for the loaf of breadd. Roast a turkeyClean turkey thoroughly, removing gibletsPlace turkey into roasting panStuff with dressing, if desiredInsert meat thermometer deeply into turkey breastCover turkey with foilRoast in 325 degree oven 4-5 hours, until appropriate internal temp isreachedRemove foilRoast until outer surfaces of turkey are browned2. Label cups: #1, #2, and #3, with #3 being the empty cupRinse #3Pour contents of #1 into #3Rinse #1Pour contents of #2 into #1Rinse #2Pour contents of #3 into #2Rinse #33. Multiply h by 50, and remember this number as hTotal Multiply q by 25, andremember this number as qTotal Multiply d by 10, and remember this number as dTotal Multiply n by 5, and remember this number as nTotal Add hTotal to qTotal to dTotal to nTotal to p, and remember this number as Total Divided Total by 100 to get the dollar amount.4. Compare first and secondIf first < second, then compare second and thirdIf second < third, then first is smallestIf second > third, then compare first and thirdIf first < third, then first is smallestIf first > third, then third is smallestIf first > second, then compare second and thirdIf second > third, then third is smallestIf second < third, then second is smallest5. a. If the number is greater than 100, keep subtracting 100 from the number.The number of times 100 was subtracted is the number of 100 bills needed.If the remaining number is greater than 50, keep subtracting 50 from the number until the number is less than 50. The number of times 50 was subtracted is the number of50 bills needed.If the remaining number is greater than 20, keep subtracting 20 from the number until the number is less than 20. The number of times 20 was subtracted is the number of20 bills needed.If the remaining number is greater than 10, keep subtracting 10 from the number until the number is less than 10.The number of times 10 was subtracted is the number of10 bills needed.If the remaining number is greater than 5, keep subtracting 5 from the number until the number is less than 5.The number of times 5 was subtracted is the number of 5 bills needed.The remaining number is then number of one-dollar bills needed.b. Total multiplied by 1 is product1Product1 is the number of $1 bills6. a. Compare the first letter of the word JONES with the first letter of each word.If the first letter is a match, compare the second letters in each word.If the second letter is a match, compare the third letters.If the third letters match, compare the fourth.If the fourth letters match, compare the fifth.If the fifth letters match, the words match.If a letter is not a match, proceed to the next word in the list and repeat thiscomparison.b. If the names are in alphabetical order you will not need to go through each namefrom the beginning of the list. You can jump to the names that begin with J, or even just jump straight to where JONES would be stored.7. Step 1: Look at the first letter. If it is an 'e' then set COUNT to 1; else set COUNT to0.Step 2: Look at the next letter. If it is 'e' then add one to COUNT.Step 3: Continue to repeat Step 2 until a period '.' is encountered.8. Step 1: Compare the number in the first position to that in the second position If thenumber in the first position is greater than the number in the second position,switch the numbersStep 2: Compare the number currently in the second position to that in the third positionIf the number in the second position is greater than the number in the thirdposition, switch the numbersStep 3: Compare the number currently in the first position to that currently in the second positionIf the number in the first position is greater than the number in the secondposition, switch the numbersExercises 1.41. 1). Specify the program ' s require:mEennstusre that the program requirement isclearly stated and that you understand what is to be achieved.2) Design and Developmen:t This includes, analyzing the problem, developing asolution, coding the solution, and testing and correcting the program.3) Documentation: Provide adequate user documentation for people who will use theprogram and programmer documentation for people who will have to maintain theprogram.4) Maintenance: Keep the solution up to date by making modifications required,whether due to changes in requirements or because errors are found during program execution.2. a. Find out exactly what the inventory problem is and what is expected of the solution.b. Contact Ms. R. Karp to either define the problem more specifically or to introduceyou to other people and/or documents that can define the problem more specifically.3. a. One output: the dollar amountb. Five inputs: half dollars, quarters, dimes, nickels, penniesc. Dollar amount = 0.50 * halfs + 0.25 * quarters + 0.10 * dimes + 0.05 * nickels +0.01 * penniesd. Dollar amount = 0.50 * 0 + 0.25 * 17 + 0.10 * 24 + 0.05 * 16 + 0.01 * 12 = 7.574. a. One output: distanceb. Two inputs: rate, elapsed timec. Distance = Rate * Timed. Distance = 55 * 2.5 = 137.5e. Divide time in minutes by 60 to convert to time in hours5. a. One output: the amount of Ergiesb. Two inputs: Fergies, Lergiesc. Ergies = Fergies * Lergiesd. Ergies = 14.65 * 4 = 58.66. a. Three lines of output.b. Three lines of input.c. Each input becomes a line of output7. a. One output: distance.b. Three inputs: s, d, and tc. Distance = s*t-0.5 * d * t * td. Dista nee = ((60*5280)/3600 * 10) -0.5 * 12 * 10 * 10 = 280 ft(Please note the student needs to first convert the 60 mph to feet/second.)8. Generally people envision only the part of the problem they are eoneerned with andin terms they are familiar with. Onee they see the effeets of the eode on the sereen, other possibilities immediately present themselves. However, onee you have eoded an applieation, making ehanges to it are generally very time eonsuming and in many eases take more time redoing than the original eoding took. This is very diffieult to explain to a elient, who generally expeets the additional eosts to be less than the original eoding eosts. In some eases the elient may tell you that you should have antieipated the problems. It is almost always better to lay out what the program will and will not do before beginning to eode the solution.9. A fixed fee is a good ehoiee if you have experienee in exaetly what is wanted, areselling an existing program to a new elient, or both you and the elient are in total agreement as to what will be produeed; otherwise, it is generally a bad ehoiee for both parties. On the positive side is that you do know how mueh you will reeeive for your work and the elient knows how mueh they will pay. The disadvantage is that unless you both are very elear as to what will be produeed, you may end up doing double and triple the amount of work eontraeted for, with very little if any additional funding. This oeeurs beeause after the elient sees the program, new featuresimmediately present themselves. You, as a programmer, may elaim these areadditional features, while the elient may elaim them as normal features that youshould have ineorporated as part of a useful program. No mater how the issue is resolved, generally, one or both sides may feel they have been deeeived.10. An hourly rate is generally preferable when the exaet nature and seope of the workis not known or elearly speeified in advanee. This is typieally a good arrangement for new projeets. When a elear understanding, in writing, is available describing what will be produced, or you are selling an application that you have previouslydeveloped, a fixed fee is generally used.11. A clearly written statement of programming work to be done is generally a good idea.The user will know exactly what the programmer is expected to do. Once theprogrammer completes the program according to the specifications his job is done.You, as the programmer, will know exactly what you need to do to fulfill your obli gation. The user can ' t decide at the last minute that he wants you to add additional features or functionality without hiring you for additional work. Thedisadvantage is that this will limit the amount of freedom you have as a programmer.You may have a better idea of how to make the program more userfriendly or easier to handle, but unless this is specified in the agreement, you need to stick with what the user originally asked for. The user also, has less freedom. Unless you both agree on any proposed changes to the agreement the user needs to stick with what was originally specified.12. (100 char / sale) x (15 sales / day) x (6 days / week) x (52 weeks /year) x 2 years =936,000 characters, or approximately 1 Million characters. Since each character isstored using 1 byte, the minimum storage is 1 Million bytes (1 MB)13. Assuming that the average typist can type 50 words per minute and that the averageword consists of 5 characters, the time it takes to enter all of the sales is [300(char/sale) x (200 sales)] / [(50 words/minute) x (5 char/word)] = (60,000 char) / (250 char/min) = 240 minutes = 4 hours of nonstop typing.Exercises 1.51. #include <stdio.h>int main(){double rad, cir; /* declare an input and output item */rad = 2.0; /* set a value for the radius */cir = 2.0 * 3.1416 * rad; /* calculate the circumference */printf("The circumference of the circle is f", cir);return 0;}2. If the area of a circle was required output, the following modifications would have tobe made to Program 1.1: Declare a variable to hold the value of the area. Add a line to calculate the area. Add a line to output the value of the area. Modify comments to reflect these changes.3. a. The value in miles of a distance given in kilometers is calculated using the formulamiles = 0.625 * kilometers. Using this information, write a C program to calculate the value in miles of 86 kilometers.b. The output required is a value in miles.c. The program will have one input (86 kilometers).d. miles = 0.625 * kilometerse. miles = 0.625 * 86 = 53.75 milesf. Get the input kilometers value Calculate miles = 0.625 * kilometers value Displaythe resulting miles value4. a. The final balance of an investment with interest compounded annually is given bythe formula balance = principal * (1.0 + rate)(final year - initial year). Using thisinformation, write a C program to calculate the final balance in 2006 of an investment initiated in 1627 with a principal of $24 and an interest rate of 5% compoundedannually.b. One output: balancec. F our inputs: principal, rate, initial year, final yeard. balance = principal * (1.0 + rate)(final year - initial year)e. balance = 24 * (1.0 + 0.05)(2006-1627) = 24 * 1.05 * 379 = 9550.80f. Get the input values principal, rate, final year, and initial year. Calculate balance =principal * (1.0 + rate)(final year - initial year) Display the resulting balance value5. a. Four outputs: the weekly gross and net pay of each individualb. Gross pay = Hourly rate * Hours workedThe general formula for calculating Net pay isNet pay = Gross pay - Tax rate * Gross pay -Medical benefits rate * Gross pay = Gross pay * (1 -Tax rate -Medical benefits rate)If the tax and benefits rates are considered as fixed numbers that will not change, this formula can be written as:Net Pay = Gross pay (1 -0.2 -0.02) = 0.78 * Gross payc. Eight inputs: the hourly rate, hours worked, income tax rate, and medical benefitsrate for each individual (Note, if you consider the tax and benefits rates as fixed, then there are four inputs)d. Gross Pay1 = $8.43 * 40 = $337.20Net Pay1 = 0.78 * $337.20 = $263.02Gross Pay2 = $5.67 * 35 = $198.45Net Pay2 = 0.78 * $198.45 = $154.79e. Get the input values Hourly rate1, Hourly rate2, Hours worked1, and Hoursworked2.Calculate Gross pay for each worker as Gross pay = Hourly rate * Hours worked.Calculate Net pay for each worker as Net pay = 0.78 * Gross pay.Display the Gross pay and Net pay values for both workers.6. a. One output: zb. Three inputs: x, u, and sc. z = (x - u) / sd. z = (85.3 - 80) / 4 = 1.325e. Get the three input values of x, u, and s.Calculate the value of the standard normal deviate (z) using the formula z = (x- u)/s.Display the z value returned by the calculation.7. a. One output: the value of yb. One input: the value of xxc. y = ed. y = 2.71810 = 22003.64e. Get the input values of e and x.Calculate the value of y using the formula y = e xDisplay the value of y.。
罗宾斯管理学第十四版——课件_ppt_01

Exhibit 1-8 Changes Facing Managers
Exhibit 1-8 shows some of the most important changes facing managers.
Types of Roles
• Interpersonal – Figurehead, leader, liaison
• Informational – Monitor, disseminator, spokesperson
• Decisional – Entrepreneur, disturbance handler, resource allocator, negotiator
Copyright © 2018 Pearson Education, Ltd. All Rights Reserved
Exhibit 1-1 Levels of Management
Exhibit 1-1 shows that in traditionally structured organizations, managers can be classified as first-line, middle, or top.
Exhibit 1-2 Characteristics of Organizations
Exhibit 1-2 shows the three common characteristics of organizations: distinct purpose, deliberate structure, and people.
Copyright © 2018 Pearson Education, Ltd. All Rights Reserved
程序类英语作文素材

程序类英语作文素材Title: The Impact of Programming on Modern Society。
Introduction:In today's technologically advanced world, programming plays a crucial role in shaping our daily lives. From smartphones to social media platforms, from self-driving cars to artificial intelligence, programming has revolutionized the way we live, work, and communicate. In this essay, we will explore the impact of programming on modern society, discussing its benefits, challenges, and future prospects.Body:1. Advancements in Communication:Programming has enabled the development of various communication tools and platforms.Social media platforms like Facebook, Twitter, and Instagram have connected people globally.Instant messaging applications like WhatsApp and WeChat have made communication faster and more convenient.Video conferencing tools like Zoom and Skype have facilitated remote collaboration and business meetings.2. Automation and Efficiency:Programming has revolutionized industries by automating repetitive and mundane tasks.Manufacturing industries now heavily rely on computer-controlled machines and robots.Automation has increased efficiency, reduced costs, and improved product quality.Businesses have adopted enterprise resource planning(ERP) systems to streamline operations and enhance productivity.3. Artificial Intelligence (AI):Programming has enabled the development of AI, which has transformed various sectors.AI-powered chatbots provide customer support and assistance.AI algorithms analyze big data to make predictions and improve decision-making.AI is used in healthcare for disease diagnosis and treatment recommendations.Self-driving cars are being developed using advanced programming techniques.4. Challenges and Concerns:The increasing reliance on programming has raised concerns about job displacement.Traditional jobs are being replaced by automation and AI.There is a need to upskill and reskill the workforce to adapt to the changing job market.Cybersecurity threats have increased with the growth of programming and digital technologies.Programmers need to develop robust security measures to protect sensitive data.5. Future Prospects:Programming will continue to play a pivotal role in technological advancements.The Internet of Things (IoT) will rely on programming to connect devices and enable communication.Blockchain technology, powered by programming, has the potential to revolutionize industries like finance and supply chain.Machine learning and data science, driven by programming, will continue to make breakthroughs in various fields.Conclusion:In conclusion, programming has had a profound impact on modern society, revolutionizing communication, automation, and artificial intelligence. While it offers numerous benefits, it also poses challenges such as job displacement and cybersecurity threats. The future prospects of programming are promising, with technologies like IoT, blockchain, and machine learning poised to reshape various industries. As programming continues to evolve, it is essential for individuals and societies to adapt and embrace the changes it brings.。
(完整word版)C++编程思想 答案 第四章 其他章节请点击用户名找 thinking in C+

[ Viewing Hints ] [ Book Home Page ] [ Free Newsletter ][ Seminars ] [ Seminars on CD ROM ] [ Consulting ]Annotated Solution GuideRevision 1.0for Thinking in C++, 2nd edition, Volume 1by Chuck Allison©2001 MindView, Inc. All Rights Reserved.[ Previous Chapter ] [ Table of Contents ] [ Next Chapter ] Chapter 44-1In the Standard C library, the function puts( ) prints a char array to the console (so you can say puts("hello")). Write a C program that uses puts( )but does not include <stdio.h>or otherwise declare the function. Compile this program with your C compiler. (Some C++ compilers are not distinct from their C compilers; in this case you may need to discover a command-line flag that forces a C compilation.) Now compile it with the C++ compiler and note the difference.(Left to the reader)4-2Create a struct declaration with a single member function, then create a definition for that member function. Create an object of your new data type, and call the member function.(see the next exercise)4-3Change your solution to Exercise 2 so the struct is declared in a properly “guarded” header file,with the definition in one cpp file and your main( ) in another. Solution://: S04:MyStruct.h#ifndef MYSTRUCT_H#define MYSTRUCT_Hstruct MyStruct {void f();};#endif ///:~//: S04:MyStruct.cpp {O}#include "MyStruct.h"#include <iostream>using namespace std;void MyStruct::f() {cout << "MyStruct::f\n";} ///:~//: S04:Exercise3.cpp//{L} MyStruct#include "MyStruct.h"int main() {MyStruct m;m.f();}///:~The #ifndef statement in MyStruct.h guarantees that the file will not be included more than once in any compilation, which isn’t an issue here, but in large projects it’s not unusual for header fil es to be logically included multiple times. The defined preprocessor operator provides an alternate means of checking for defined preprocessor symbols, as follows:#if !defined(MYSTRUCT_H)This form allows multiple conditions to be tested with logical connectives such as ||and &&.4-4Create a struct with a single int data member, and two global functions, each of which takes a pointer to that struct. The first function has a second int argument and sets the struct’s int to the argument value, the second displays the int from the struct. Test the functions.(see the next exercise...)4-5Repeat Exercise 4 but move the functions so they are member functions of the struct, and test again.Solution://: S04:GetSet.cpp#include <iostream>using namespace std;struct HasInt {int x;void setInt(int newX) {x = newX;}int getInt() {return x;}};int main() {HasInt h;h.setInt(5);cout << h.getInt() << endl; // 5}///:~It is very common for a class to have such get- and set-members like this one does. In this example I could have separated the class definition and the member function implementation like I did in exercise number 3 above, but I didn’t for two reasons: 1) I’m lazy, and 2) I wanted to remind you that when you define member function bodies in situ like this (i.e., inside the class definition), they are implicitly inline functions.4-6Create a class that (redundantly) performs data member selection and a member function call using the this keyword (which refers to the address of the current object).Solution://: S04:UsesThis.cpp#include <iostream>using namespace std;struct HasInt {int x;void setInt(int x) {this->x = x;}int getInt() {return this->x;}void display() {cout << this->getInt() << endl;}};int main() {HasInt h;h.setInt(5);h.display(); // 5}///:~This is a variation on the previous exercise. The use of this is actually necessary in HasInt::setInt to disambiguate the parameter x from the member x.4-7Make a Stash that holds double s. Fill it with 25 double values, then print them out to the console. (Left to the reader)4-8Repeat Exercise 7 with Stack.(Left to the reader)4-9Create a file containing a function f( ) that takes an int argument and prints it to the console using the printf( ) function in <stdio.h> by saying: printf(“%d\n”, i) in which i is the int you wish to print. Create a separate file containing main( ), and in this file declare f( ) to take a float argument. Call f( ) from inside main( ). Try to compile and link your program with the C++ compiler and see what happens. Now compile and link the program using the C compiler, and see what happens when it runs. Explain the behavior.Solution:This exercise illustrates type-safe linkage. In C++ function name are decorated (aka mangled) to include information about their arguments. The consequence is that the name the linker sees is actually quite different than what you see. For example, f(int) might appear to the linker as f_F1i (a function taking one int), say, and f(double) as f_F1d. Since the names are distinct, you get a linker error. In C the names are the same, allowing you to call f(double) with an int, which is an error.4-10Find out how to produce assembly language from your C and C++ compilers. Write a function in C and a struct with a single member function in C++. Produce assembly language from each and find the function names that are produced by your C function and your C++ member function, so you can see what sort of name decoration occurs inside the compiler.Solution:For f(int) one compiler generated the name ?f@@YAXH@Z, and ?f@@YAXN@Z forf(double). Go figure.4-11Write a program with conditionally-compiled code in main( ), so that when a preprocessor value is defined one message is printed, but when it is not defined another message is printed. Compile this code experimenting with a #define within the program, then discover the way your compiler takes preprocessor definitions on the command line and experiment with that.(Left to the reader)4-12Write a program that uses assert( ) with an argument that is always false (zero) to see what happens when you run it. Now compile it with #define NDEBUG and run it again to see the difference.(Left to the reader)4-13Create an abstract data type that represents a videotape in a video rental store. Try to consider all the data and operations that may be necessary for the Video type to work well within the video rental management system. Include a print( ) member function that displays information about the Video.(Left to the reader)4-14Create a Stack object to hold the Video objects from Exercise 13. Create several Video objects, store them in the Stack, then display them using Video::print( ).(Left to the reader)4-15Write a program that prints out all the sizes for the fundamental data types on your computer using sizeof( ).Solution://: S04:Sizeof.cpp#include <iostream>int main() {using namespace std;cout << sizeof(char) << endl;cout << sizeof(short) << endl;cout << sizeof(int) << endl;cout << sizeof(long) << endl;cout << sizeof(float) << endl;cout << sizeof(double) << endl;cout << sizeof(long double) << endl;}/* Output:1244488*////:~As you can see above, this particular (32-bit) compiler uses the same size for int and long, and for double and long double. Another compiler I have uses 10 bytes for a long double, giving greater precision for numeric calculations.4-16Modify Stash to use a vector<char> as its underlying data structure.(Left to the reader)4-17Dynamically create pieces of storage of the following types, using new: int, long, an array of 100 char s, an array of 100 float s. Print the addresses of these and then free the storage using delete.Solution://: S04:Storage.cpp#include <iostream>int main() {using namespace std;int* p_int = new int;long* p_long = new long;char* p_chars = new char[100];float* p_floats = new float[100];cout << "p_int == " << p_int << endl;cout << "p_long == " << p_long << endl;cout << "p_chars == " << static_cast<void*>(p_chars) << endl;cout << "p_floats == " << p_floats << endl;delete p_int;delete p_long;delete [] p_chars;delete [] p_floats;}/* Output:// Compiler A:p_int == 00673384p_long == 00673394p_chars == 006733A4p_floats == 0067340C// Compiler B:p_int == 00770950p_long == 00770940p_chars == 007708D0p_floats == 00770630*////:~The static_cast above is necessary because the output stream insertion operator is overloaded to treat a char* as a null-terminated string. All other pointers have their addresses printed out in hexadecimal. Don’t forget to use the brackets wi th delete for arrays. Notice that the way a compiler allocates things on the stack is its business –don’t count on any common behavior across platforms.4-18Write a function that takes a char*argument. Using new, dynamically allocate an array ofchar that is the size of the char array that’s passed to the function. Using array indexing, copy the characters from the argument to the dynamically allocated array (don’t forget the null terminator) and return the pointer to the copy. In your main( ), test the function by passing a static quoted character array, then take the result of that and pass it back into the function. Print both strings and both pointers so you can see they are different storage. Using delete, clean up all the dynamic storage.Solution://: S04:StringCopy.cpp#include <iostream>#include <cstring>#include <cstddef> // For size_tusing namespace std;char* copy(char* s1) {size_t len = strlen(s1);char* s2 = new char[len + 1];strcpy(s2, s1);return s2;}int main() {char* first = "Read my lips";char* second = copy(first);cout << "first == \"" << first << "\" at "<< static_cast<void*>(first) << endl;cout << "second == \"" << second << "\" at "<< static_cast<void*>(second) << endl;delete [] second;}/* Output:first == "Read my lips" at 0041914Csecond == "Read my lips" at 00673384*////:~The copy function above uses two library functions defined in <cstring>: strlen to determine the length of the incoming string, and strcpy to copy one string to another (including the null terminator). size_t is an unsigned integer type (usually unsigned int) defined in various places, including <iostream>, and is the return type of strlen. See the previous exercise for an explanation of the casts used.4-19Show an example of a structure declared within another structure (a nested structure). Declare data members in both struct s, and declare and define member functions in both struct s. Write a main( ) that tests your new types.Solution://: S04:Nested.cpp#include <iostream>struct Outer {int o;void setO(int n) {o = n;}int getO() {return o;}struct Inner {int i;void setI(int n) {i = n;}int getI() {return i;}};};int main() {using namespace std;Outer o;o.setO(1);cout << o.getO() << endl;Outer::Inner i;i.setI(2);cout << i.getI() << endl;}/* Output:12*////:~Declaring a struct within a struct places the inner in the scope of the outer. For this reason I have to use the expression Outer::Inner above. Nesting structures in this fashion shows an ownership relationship between types and also minimizes the chance of name conflict in the global namespace.4-20How big is a structure? Write a piece of code that prints the size of various structures. Create structures that have data members only and ones that have data members and function members. Then create a structure that has no members at all. Print out the sizes of all these. Explain the reason for the result of the structure with no data members at all.Solution://: S04:StructSize.cpp#include <iostream>struct DataOnly {int x;};struct Both {int x;void setX(int);int getX();};struct Nothing {};int main() {using namespace std;cout << sizeof(DataOnly) << endl;cout << sizeof(Both) << endl;cout << sizeof(Nothing) << endl; }/* Output:441*////:~As you can see in this program, the presence of a (non-virtual) member function does not affect the size of a struct. (NOTE: this is only true for classes with no virtual functions – see Chapter 15). The standard requires all struct s to have non-zero size, even if they have no members. This is so that distinct objects of any type will have distinct memory addresses.4-21C++ automatically creates the equivalent of a typedef for struct s, as you’ve seen in this chapter. It also does this for enumerations and unions. Write a small program that demonstrates this.(Left to the reader)4-22Create a Stack that holds Stash es. Each Stash will hold five lines from an input file. Create the Stash es using new. Read a file into your Stack, then reprint it in its original form by extracting it from the Stack.(Left to the reader)4-23Modify Exercise 22 so that you create a struct that encapsulates the Stack of Stash es. The user should only add and get lines via member functions, but under the covers the struct happens to use a Stack of Stash es.(Left to the reader)4-24Create a struct that holds an int and a pointer to another instance of the same struct. Write a function that takes the address of one of these struct s and an int indicating the length of the list you want created. This function will make a whole chain of these struct s (a linked list), starting from the argument (the head of the list), with each one pointing to the next. Make the new struct s using new, and put the count (which object number this is) in the int. In the last struct in the list, put a zero value in the pointer to indicate that it’s the end. Write a second function that takes the head of your list and moves through to the end, printing out both the pointer value and the int value for each one.(Left to the reader)4-25Repeat Exercise 24, but put the functions inside a struct instead of using “raw” struct s and functions.Solution://: S04:LinkedList.cpp#include <iostream>#include <cassert>using namespace std;struct Node {int val;Node* next;};void create(Node* head, int howMany) {assert(head);Node* p1 = head;for (int i = 1; i < howMany; ++i) {Node* p2 = new Node;p2->val = i;p1->next = p2;p1 = p2;}p1->next = 0;}void display(Node* node) {assert(node);while (node) {cout << node->val << " (at " << node << ")\n";node = node->next;}}void cleanup(Node* node) {if (node) {cleanup(node->next);cout << "deleting Node at " << node << endl;delete node;}}int main() {Node* head = new Node;head->val = 0;create(head, 10);display(head);cleanup(head);}/* Output:0 (at 00770950)1 (at 00770940)2 (at 00770930)3 (at 00770920)4 (at 00770910)5 (at 00770900)6 (at 007708F0)7 (at 007708E0)8 (at 007708D0)9 (at 007707C0)deleting Node at 007707C0 deleting Node at 007708D0 deleting Node at 007708E0deleting Node at 007708F0deleting Node at 00770900deleting Node at 00770910deleting Node at 00770920deleting Node at 00770930deleting Node at 00770940deleting Node at 00770950*////:~The loop in create( )starts at 1 since I’m assuming the head node to be the 0-th node. Inside the loop, p2-next is uninitialized, but it gets set (as p1) on the next iteration, and the last one (outside the loop) is set to 0 (the null pointer), marking the end of the list.The cleanup( ) function frees all the heap memory by recursively traversing the list until it hits the null pointer, then deletes each node as it traces back up the call stack. It is crucial in this version of main( ) that the head node was also allocated from the heap. Otherwise I could just callcleanup(head->next) to ignore that node and deallocate the rest.4-26Write a function that takes two int arguments, rows and columns. This function returns a pointer to a dynamically allocated two-dimensional array of float. As a hint, the first call to new is: new float[rows][]. This must be followed by multiple calls to new in order to create all the storage for the rows. Write a second function that takes this “matrix” and frees the storage using delete. Now convert the code into a struct called matrix.(Left to the reader)[ Previous Chapter ] [ Table of Contents ] [ Next Chapter ]Last Update:06/27/2002。
1 Introduction to Computer Programming

A First Book of ANSI C, Fourth Edition
2
History and Hardware
• Babbage’s analytical engine (1822) • Atanasoff-Berry Computer (ABC, 1937)
– Human operator manipulated external wiring
– A program or set of programs is called software
• Programming: writing instructions in a language that the computer can respond to and that other programmers can understand • Programming language: set of instructions that can be used to construct a program
A First Book of ANSI C, Fourth Edition 15
Assembly Language
• Assembly language: uses the substitution of wordlike symbols for the opcodes, and decimal numbers and labels for memory addresses
– Every section of memory can be accessed randomly as quickly as any other section – Volatile: data is lost when power is turned off
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
e.g. scanf("a=%d, b=%d", &a, scanf("%d, %d", &a, &b); &b); Form: input: scanf ("control b=345↵ arg1, …, argn); a=12, string", 12, 345↵ result: 12⇒a, 345⇒b e.g. scanf("%d,%c", &num, &ch);
1 %d, %i Signed decimal integer 2 %x, %X Unsigned hexadecimal integer (without leading 0x) 3 %o Unsigned octal integer (without leading 0) 4 %u Unsigned decimal integer 5 %c Single character 6 %s Sting 7 %f Real number in decimal notation 8 %e, %E Real number in exponential notation Real number either f-type or e-type depending on 9 %g, %G the length of the value without insignificant zero 10 %% %
6
3/5/2011
printf( ) – Formatted Output
Accessorial format specifications
1 w Specifies the minimum field width for the output. To real number, specifies the number of digits after the decimal point (rounded). To string, instructs the first p characters to be outputted. To integer or single character, it is invalid. Precede d, i, o, x, u to outputs long type integer. Precede f, e, g to outputs double type real number. Left-justified, and remaining field will be blank.
h l w * Precede d, i, o, u, x to read short type integer. Precede d, i, o, x, u to read long type integer. Precede f, e, g to read double type real number. Specify the field width of the data to be read. Specify the input field to be skipped.
7
3/5/2011
scanf( ) – Formatted Input
Form: e.g.
1.
scanf ("control string", arg1, …, argn); scanf("%d,%c", &num, &ch);
format specifications %d, %i, %o, %x, %u, %c, %s, %f, %e, %g the same as those in printf function.
11
3/5/2011
scanf( ) – Formatted Input
Form: e.g. scanf ("control string", arg1, …, argn); scanf("%d%c", &i, &ch); input: 12 a↵ e.g. scanf("%d,%c", &num, &ch); result: 12⇒i, ' ' ⇒ch Separators
3.
input: Separators result:
②
12, 345↵ 12 345↵ 12⇒a, nothing⇒b nothing⇒a, nothing⇒b
It also can specify separators, that is those characters except format specifications. In this way, the input must accord with the specified format, otherwise the input most probably is read in by errors.
Escape sequence characters. Format specifications.
e.g. %f, %d
4
3/5/2011
printf( ) – Formatted Output
Form: printf("control string", arg1, …, argn);
e.g. printf("price=$%.2f\n, amount=%d.", pr*am, am);
printf( ) putchar( )
standard input and output
2
3/5/2011
getchar( ) & putchar( )
Form: #include <stdio.h> variable = getchar(); main() putchar(character); { char c ; c = getchar ( ); putchar ( c ); putchar ( getchar () ); printf ( "%c", getchar () ); putchar ('D'); } printf("%d", getchar()); }
2.
printf("%c, %d", 97, 'a'); The outputted expression list: (arg1, …, argn) Output: a, 97 There can be no any expression or more than one expression. They are separated by comma. printf("%d, %u", 32767+1, 32767+1); Output: -32768, 32768 In spite of what type these expressions are, they are always outputted in specified format.
③
3.
When it read in a character, the blank space, tab and newline character are no longer separators, but as a valid character.
12
3/5/2011
scanf( ) – Formatted Input
8
3/5/2011
scanf( ) – Formatted Input
e.g.
scanf("%d%*d%d", &a, &b); input: 12 345 67↵ Form: scanf ("control string", arg1, …, argn); result: 12⇒a, 67⇒b e.g. scanf("%d,%c", &num, &ch); &i, &f); scanf("%3d%f", &i, &f); scanf("%3d%*2d%f", e.g. input: 12345.6789↵ 123456.789↵ 2. Accessorial format 123⇒i, 45.6789⇒f specifications result: 6.789⇒f
Chapter 4 Managing Input and Output Operations
PROGRAMMING IN ANSI C
3/5/2011
Chapter 4
C hasn’t any built-in input/output statements as part of its syntax. All of input/output operations are carried out through standard input/output functions. scanf( ) getchar( ) gets( ) puts( ) e.g. printf( ) # include <stdio.h> # include "stdio.h"
2
.p
3 4