Pascalabc.NET: Выбор Школьника. Часть 1

Total Page:16

File Type:pdf, Size:1020Kb

Pascalabc.NET: Выбор Школьника. Часть 1 Александр Осипов PascalABC.NET: выбор школьника Часть 1 Почему PascalABC.NET? Базовые знания Линейные алгоритмы Алгоритмы с ветвлением Циклические алгоритмы Pascal в КИМ ЕГЭ и ОГЭ 70 типичных задач: постановка, математическая модель, программный код Ростов-на-Дону 2020 УДК 004.432 ББК 32.973 О741 Рецензенты: - кандидат физико математических наук, доцент кафедры алгебрыС. С. Михалков и дискретнойич математики Южного федерального университета - кандидат физико математических наук, доцент, заведующий кафедройВ. О. Дженжер информатики, физики и МПИФ Оренбургского государственного педагогического университета Осипов А. В. PascalABC.NET — 2- – - - О741 : выбор школьника. Часть 1. – 48е изд., испр. и доп., /А. В. Осипов. Ростов на Дону; Таганрог : Издательство Южного федерального университета,– 2020. 1 с. Целевая аудитория книги школьники и учащиеся иных общеобразовательных учреждений среднего образования Книга можетPascal быть. также полезна студентам младших курсов, учителям и преподавателям, интересующимся решением задач в современной версии языка Приводится теорияPascalABC и дается.NET. решение задач по программированию из школьного курса информатики с максимальным использованием– возможностей Подборка задач позволяет использовать книгу в качестве ныне популярного «решебника», но главная цель научиться писать современный короткий, понятный и эффективный код. УДК 004.432 © ББК 32.973 А. В. Осипов, 2020 © Южный федеральный университет, 2020 Оглавление 3 .............................................................................................................................. PascalABC.NET .......................................................... Оглавление 3 ................................................................................................. Предисловие разработчика 7 ................................................................................................................................. Предисловие рецензента 9 ................................................................................................ От автора 11 ............................................................. Глава 1. Базовые знания 13 .......................................................... 1.1. Почему именно PascalABC.NET? 14 ...................................................................... 22 1.2. Основная программа и ее запись 19 ............................................................................................. 22 1.3. Простейший вывод данных .................................................................... 24 1.3.1. Вывод текста ....................................................... 25 1.3.2. Вывод числовых данных .......................................................... 26 1.4. Основные числовые типы данных ............................................... 28 1.4.1. Данные целого типа (integer) ....................................... 1.4.2. Данные вещественного типа (real) ............................................................................................... 1.5. Построение арифметических выражений 30 ............................................................... 1.5.1. Переменные 30 ...................................... 1.5.2. Арифметические операции 33 ......................................................................... 1.5.3. Приоритет арифметических операций 34 ............................................................................. 1.5.4. Стандартные функции 36 ...................................................................................................... 1.6. Оператор присваивания 37 ......................................................................................................... 1.7. Ввод данных 38 ................................................................................... 1.8. О ЕГЭ и ОГЭ 40 .................................................................... 45 Глава 2. Линейные алгоритмы 43 ............................................................................................... 45 2.1. Целочисленная арифметика ................. 48 2.1.1. Перевод мер 2.2. .................................... 2.1.2. Выделение цифр в числе заданной разрядности Арифметика вещественных и целых чисел 49 4 ........................................ 2.2.2. .................................. 2.2.1. Вычисления по известным формулам 50 ............................................................................... 54 Вычисления по формулам из геометрии 51 ............................................................................ 2.2.3. Прочие вычисления ............................................................................. 58 Глава 3. Алгоритмы с ветвлением 57 .............................................................................. 3.1. Логический тип данных ........................................................................... 3.2. Логические выражения 59 ........................................................................... 3.2.1. Операции отношения 59 ................................................................................ 3.2.2. Логические операции 60 ....................................................................................... 62 3.2.3. О «короткой схеме» 61 ........................................................................................ 64 3.3. Условный оператор ......................................... 66 3.4. Условная операция .................................................. 66 3.5. Алгоритмы без множественного выбора ........................................ 3.5.1. Поиск минимумов и максимумов - ............................................................. 3.5.2. Попадание точки в заданную область 67 .......................... 3.5.3. Кусочно заданные функции 70 ....................... 3.5.4. Анализ цифр в числе заданной разрядности 72 ................................................................. 3.5.5. Решение линейных и квадратных уравнений 75 ............................................................................................ 82 3.5.6. Геометрия в вычислениях 79 ........................................ 84 3.6. Оператор выбора ............................................................................. 3.7. Алгоритмы со множественным выбором ................................. 88 Глава 4. Циклические алгоритмы 87 4.2. ............................................................................. 88 4.1. Цикл с заданным числом повторений (loop) ................................................................... Цикл с параметром (for) 4.4. .................................................................. 4.3. Цикл с предусловием (while) 90 4.5. .................................................... Цикл с постусловием (repeat) 90 ......................................................................................... Изменение хода выполнения цикла 91 4.5.1. Оператор break 91 5 4.5.2. ................................................................................... .............................................................................................. Оператор continue 91 4.6. ......................................................................................... 4.5.3. Оператор exit 91 ......................................................... Вложенные циклы 92 ............................... 4.7. Задачи с использованием циклов 92 ..................... 4.7.1. Ввод нескольких групп исходных данных 92 ........................... 4.7.2. Ряды значений, вычисляемых по их позициям 95 .......................... 4.7.3. Ряды значений, вычисляемых рекуррентно 99 ................................ 4.7.4. Анализ цифр в произвольном целом числе 103 .................................... 4.7.5. Табуляция функции одной переменной 106 .................................................................... 4.7.6. Табуляция функции двух переменных 111 ....................................................................................... 4.7.7. Нахождение НОД и НОК 113 ...................................... 4.7.8. Простые числа 115 4.8. ....................................................... 4.7.9. Задача о сдаче («жадный» алгоритм) 117 ............................................ Использование случайных чисел 119 ................................................... 4.9. Перевод между системами счисления 123 N ........................................... 4.9.1. Перевод в десятичную систему 123 ....................................................... 4.9.2. Перевод в систему по основанию 124 ....................................... 4.10. Нахождение делителей числа 127 ............................. 4.10.1. Нахождение всех делителей числа 127 . ............................................. 4.10.2. Нахождение простых делителей числа 128 ............................................................................. 4.11. Решение задачи с сайта //acmp ru 129 ....................................................................................................................... 4.12. Вместо заключения 131 ........................................................ Приложения 133 ............................................................................ П1. Прямоугольная система координат 134 ............................................................................ П2. Уравнения плоских линий 135 .......................................................... П3. Геометрия в вычислениях 138 П4. Нахождение сумм и произведений 139 6 ................................................................................ .....................................................................
Recommended publications
  • KDE 2.0 Development, Which Is Directly Supported
    23 8911 CH18 10/16/00 1:44 PM Page 401 The KDevelop IDE: The CHAPTER Integrated Development Environment for KDE by Ralf Nolden 18 IN THIS CHAPTER • General Issues 402 • Creating KDE 2.0 Applications 409 • Getting Started with the KDE 2.0 API 413 • The Classbrowser and Your Project 416 • The File Viewers—The Windows to Your Project Files 419 • The KDevelop Debugger 421 • KDevelop 2.0—A Preview 425 23 8911 CH18 10/16/00 1:44 PM Page 402 Developer Tools and Support 402 PART IV Although developing applications under UNIX systems can be a lot of fun, until now the pro- grammer was lacking a comfortable environment that takes away the usual standard activities that have to be done over and over in the process of programming. The KDevelop IDE closes this gap and makes it a joy to work within a complete, integrated development environment, combining the use of the GNU standard development tools such as the g++ compiler and the gdb debugger with the advantages of a GUI-based environment that automates all standard actions and allows the developer to concentrate on the work of writing software instead of managing command-line tools. It also offers direct and quick access to source files and docu- mentation. KDevelop primarily aims to provide the best means to rapidly set up and write KDE software; it also supports extended features such as GUI designing and translation in con- junction with other tools available especially for KDE development. The KDevelop IDE itself is published under the GNU Public License (GPL), like KDE, and is therefore publicly avail- able at no cost—including its source code—and it may be used both for free and for commer- cial development.
    [Show full text]
  • Note on Using the CS+ Integrated Development Environment
    Tool News RENESAS TOOL NEWS on April 16, 2015: 150416/tn2 Note on Using the CS+ Integrated Development Environment When using the CS+ IDE, take note of the problem described in this note regarding the following point. Statements in source code which form a deeply-nested block 1. Products Concerned Products from the following list for which the version number of the CS+ common program is 3.00.00 to 3.01.00. - RX Family C/C++ Compiler Package (with IDE) - RL78 Family C Compiler Package (with IDE) - RH850 Family C Compiler Package (with IDE) - CS+ evaluation edition To check the version number of the product you have, refer to the following URL. https://www.renesas.com/cubesuite+_ver 2. Description CS+ might be terminated forcibly when a program is downloaded to a debugging tool or when an editor panel is opened after downloading a program. 3. Conditions Forced termination may occur when the source code for a project includes code that meets any of the following conditions. (a) { } blocks nested to a depth of 128 or more within a function. (b) 64 or more consecutive "else if" conditions are in sequence. (c) The total of double the number of consecutive "else if" conditions and the depth of the nesting of {} blocks at some point in the sequence of consecutive "else if" conditions is 128 or more. With conditions (b) and (c) above, the problem only arises when the C99 option is designated and the product is the RX family C/C++ compiler package (with IDE). 4. Workaround To avoid this problem, do any of the following.
    [Show full text]
  • Renamer User Manual
    ReNamer User Manual www.den4b.com PDF generated using the open source mwlib toolkit. See http://code.pediapress.com/ for more information. PDF generated at: Thu, 31 Mar 2016 23:44:52 CEST Contents Articles Basics 1 ReNamer 1 Introduction 2 Quick Guide 3 Step-by-step 4 Adding files and folders 4 Managing Rules 8 Previewing Files 11 Renaming Files 12 Rules 14 Using the Rules 14 Overview of Rules 14 Insert Rule 15 Delete Rule 17 Remove Rule 18 Replace Rule 20 Rearrange Rule 22 Extension Rule 24 Strip Rule 25 Case Rule 26 Serialize Rule 28 CleanUp Rule 30 Translit Rule 31 RegEx Rule 35 PascalScript Rule 37 UserInput Rule 40 ReformatDate Rule 42 Pascal Script 44 Pascal Script 44 Quick Guide 46 Types 49 Functions 51 User Scripts 65 Appendices 67 Using Presets 67 Manual Editing 73 Analyze 75 Program settings 76 Main Menu and Keyboard Shortcuts 82 Menus for the Files Pane 84 Context Menus 91 Date and Time Format 93 Binary Signatures 94 Meta Tags 97 Analyze 98 Regular Expressions 100 Command Line Mode 107 Sorting Files 110 Using Masks 111 Renaming Folders 111 Renaming to Another Folder 112 Failed Renaming 114 Validation of New Names 115 Examples of rules 115 Examples of Rearrange rule 117 References Article Sources and Contributors 128 Image Sources, Licenses and Contributors 130 Article Licenses License 132 1 Basics ReNamer ReNamer is a very powerful and flexible file renaming tool. ReNamer offers all the standard renaming procedures, including prefixes, suffixes, replacements, case changes, removing the content inside brackets, adding number sequences, changing file extensions, etc.
    [Show full text]
  • Embrace and Extend Approach (Red Hat, Novell)
    Integrated Development Environments (IDEs) Technology Strategy Chad Heaton Alice Park Charles Zedlewski Table of Contents Market Segmentation.............................................................................................................. 4 When Does the IDE Market Tip? ........................................................................................... 6 Microsoft & IDEs ................................................................................................................... 7 Where is MSFT vulnerable?................................................................................................. 11 Eclipse & Making Money in Open Source........................................................................... 12 Eclipse and the Free Rider Problem ..................................................................................... 20 Making Money in an Eclipse World?................................................................................... 14 Eclipse vs. Microsoft: Handicapping the Current IDE Environment ................................... 16 Requirements for Eclipse success......................................................................................... 18 2 Overview of the Integrated Development Environment (IDE) Market An Integrated Development Environment (IDE) is a programming environment typically consisting of a code editor, a compiler, a debugger, and a graphical user interface (GUI) builder. The IDE may be a standalone application or may be included as part of one or more existing
    [Show full text]
  • The C Programming Language
    The C programming Language The C programming Language By Brian W. Kernighan and Dennis M. Ritchie. Published by Prentice-Hall in 1988 ISBN 0-13-110362-8 (paperback) ISBN 0-13-110370-9 Contents ● Preface ● Preface to the first edition ● Introduction 1. Chapter 1: A Tutorial Introduction 1. Getting Started 2. Variables and Arithmetic Expressions 3. The for statement 4. Symbolic Constants 5. Character Input and Output 1. File Copying 2. Character Counting 3. Line Counting 4. Word Counting 6. Arrays 7. Functions 8. Arguments - Call by Value 9. Character Arrays 10. External Variables and Scope 2. Chapter 2: Types, Operators and Expressions 1. Variable Names 2. Data Types and Sizes 3. Constants 4. Declarations http://freebooks.by.ru/view/CProgrammingLanguage/kandr.html (1 of 5) [9/6/2002 12:20:42 ] The C programming Language 5. Arithmetic Operators 6. Relational and Logical Operators 7. Type Conversions 8. Increment and Decrement Operators 9. Bitwise Operators 10. Assignment Operators and Expressions 11. Conditional Expressions 12. Precedence and Order of Evaluation 3. Chapter 3: Control Flow 1. Statements and Blocks 2. If-Else 3. Else-If 4. Switch 5. Loops - While and For 6. Loops - Do-While 7. Break and Continue 8. Goto and labels 4. Chapter 4: Functions and Program Structure 1. Basics of Functions 2. Functions Returning Non-integers 3. External Variables 4. Scope Rules 5. Header Files 6. Static Variables 7. Register Variables 8. Block Structure 9. Initialization 10. Recursion 11. The C Preprocessor 1. File Inclusion 2. Macro Substitution 3. Conditional Inclusion 5. Chapter 5: Pointers and Arrays 1.
    [Show full text]
  • FEI~I<Ts Ltistttute NEWS LETTER
    NEWS LETTER FEI~I<tS ltiSTtTUTE from l\Yron J. Brophy, President VOL. 1. NO.7 Big Rapids, !.Iichigan July 23, 1951 . BUlmmG ffiOOR,i1SS. Mon~ Progress Meeting was held at the site at 1 p.m. Wednesday, Jul¥ lB. Those present were: For the Institution" . President Brophy, It'. Pattullo" and Mr. DeMOSS; for the Building Division" Mr. J. ~-'angema.n, and 11:r. Arthur Decker, the project Superintendent; for the IJuskegon Construction Company, Mr. Smith and Mr. Mastenbrook; fC1!.' t...~e Distel Heating Company, ur. Holgate; and for the Electric Construction t.; Machiner"J COmpany, ur. Brabon and Mr. Knight,; and for the Architect, l!r'. Roger Allen. Mr. Allen reported that the color scheme for all rooms in the East Wing has been determined. Mr. lD:rnest King, from the architect1s office, conferred With l!r. pattullo Friday to discuss the preparation of similar color schemes for the Vlest Wing. Work on General C~struction is proceeding rapidq and all mechanical contractors are keeping up with the construction. All structural steel roof framing for the one-story sections will be in place by the middle of this 'week and will be ready to receiVe steel roof deck. ];!t'. Smith hB.f3 received word from the Detroit Steel Products Company (sub­ contractors for the steel deck) that this material Will be Shipped some­ time bet\"loon July 30th and August loth. The fin!ll poUring of cement sla.bin the classroom building was completed last l'leck. The stone Window Sills have been received and installation has started. The alllnlinum vlindow frames Bl'e now being in­ stalled and arc ready for the laying of the glass blockS.
    [Show full text]
  • 2.3.7 80X86 Floating Point
    Open Watcom C/C++ Compiler Options data segment. For example, the option "zt100" causes all data objects larger than 100 bytes in size to be implicitly declared as far and grouped in other data segments. The default data threshold value is 32767. Thus, by default, all objects greater than 32767 bytes in size are implicitly declared as far and will be placed in other data segments. If the "zt" option is specified without a size, the data threshold value is 256. The largest value that can be specified is 32767 (a larger value will result in 256 being selected). If the "zt" option is used to compile any module in a program, then you must compile all the other modules in the program with the same option (and value). Care must be exercised when declaring the size of objects in different modules. Consider the following declarations in two different C files. Suppose we define an array in one module as follows: extern int Array[100] = { 0 }; and, suppose we reference the same array in another module as follows: extern int Array[10]; Assuming that these modules were compiled with the option "zt100", we would have a problem. In the first module, the array would be placed in another segment since Array[100] is bigger than the data threshold. In the second module, the array would be placed in the default data segment since Array[10] is smaller than the data threshold. The extra code required to reference the object in another data segment would not be generated. Note that this problem can also occur even when the "zt" option is not used (i.e., for objects greater than 32767 bytes in size).
    [Show full text]
  • What Is Inno Setup? Inno Setup Version 5.5.6 Copyright © 1997-2015 Jordan Russell
    What is Inno Setup? Inno Setup version 5.5.6 Copyright © 1997-2015 Jordan Russell. All rights reserved. Portions Copyright © 2000-2015 Martijn Laan. All rights reserved. Inno Setup home page Inno Setup is a free installer for Windows programs. First introduced in 1997, Inno Setup today rivals and even surpasses many commercial installers in feature set and stability. Key features: Support for every Windows release since 2000, including: Windows 10, Windows 8, Windows Server 2012, Windows 7, Windows Server 2008 R2, Windows Vista, Windows Server 2008, Windows XP, Windows Server 2003, and Windows 2000. (No service packs are required.) Extensive support for installation of 64-bit applications on the 64-bit editions of Windows. Both the x64 and Itanium architectures are supported. (On the Itanium architecture, Service Pack 1 or later is required on Windows Server 2003 to install in 64-bit mode.) Supports creation of a single EXE to install your program for easy online distribution. Disk spanning is also supported. Standard Windows wizard interface. Customizable setup types, e.g. Full, Minimal, Custom. Complete uninstall capabilities. Installation of files: Includes integrated support for "deflate", bzip2, and 7-Zip LZMA/LZMA2 file compression. The installer has the ability to compare file version info, replace in-use files, use shared file counting, register DLL/OCX's and type libraries, and install fonts. Creation of shortcuts anywhere, including in the Start Menu and on the desktop. Creation of registry and .INI entries. Running other programs before, during or after install. Support for multilingual installs, including right-to-left language support. Support for passworded and encrypted installs.
    [Show full text]
  • Top Productivity Tips for Using Eclipse for Embedded C/C++ Developers
    Top Productivity Tips for Using Eclipse for Embedded C/C++ Developers Garry Bleasdale, QNX Software Systems, [email protected] Andy Gryc, QNX Software Systems, [email protected] Introduction This paper presents a selection of Eclipse IDE tips and tricks gathered from: the QNX® development community: our engineers, techies and trainers Foundry27, the QNX Community Portal for open development, where we have an Eclipse IDE forum Eclipse.org forums public web sites and blogs that offer Eclipse-related expertise The 27 tips described in this paper are the tips that we received from these sources and identified as most interesting and useful to developers. We present them here with the hope that they will help make you more productive when you use the Eclipse IDE. About Eclipse A modern embedded system may employ hundreds of software tasks, all of them sharing system resources and interacting in complex ways. This complexity can undermine reliability, for the simple reason that the more code a system contains, the greater the probability that coding errors will make their way into the field. (By some estimates, a million lines of code will ship with at least 1000 bugs, even if the code is methodically developed and tested.) Coding errors can also compromise security, since they often serve as entry points for malicious hackers. No amount of testing can fully eliminate these bugs and security holes, as no test suite can anticipate every scenario that a complex software system may encounter. Consequently, system designers and software developers must adopt a “mission-critical mindset” and employ software architectures that can contain software errors and recover from them quickly.
    [Show full text]
  • TMS Scripter Documentation
    Overview TMS Scripter is a set of Delphi/C++Builder components that add scripting capabilities to your applications. With TMS Scripter your end-user can write his own scripts using visual tools and then execute the scripts with scripter component. Main components available are: • TatScripter: Non-visual component with cross-language support. Executes scripts in both Pascal and Basic syntax. • TatPascalScripter: Non-visual component that executes scripts written in Pascal syntax. • TatBasicScripter: Non-visual component that executes scripts written in Basic syntax. • TScrMemo: Lightweight syntax highlight memo, that can be used to edit scripts at run- time. TatScripter, TatPascalScripter, TatBasicScripter and TIDEScripter (in this document, all of these componentes are just called Scripter) descend from TatCustomScripter component, which has common properties and methods for scripting execution. The scripter has the following main features: • Run-time Pascal and Basic language interpreter; • Access any Delphi object in script, including properties and methods; • Supports try..except and try..finally blocks in script; • Allows reading/writing of Delphi variables and reading constants in script; • Allows access (reading/writing) script variables from Delphi code; • You can build (from Delphi code) your own classes, with properties and methods, to be used in script; • Most of Delphi system procedures (conversion, date, formatting, string-manipulation) are already included (IntToStr, FormatDateTime, Copy, Delete, etc.); • You can save/load compiled code, so you don't need to recompile source code every time you want to execute it; • Debugging capabilities (breakpoint, step into, run to cursor, pause, halt, and so on); • Thread-safe; • COM (Microsoft Common Object Model) Support; • DLL functions calls.
    [Show full text]
  • Using the Java Bridge
    Using the Java Bridge In the worlds of Mac OS X, Yellow Box for Windows, and WebObjects programming, there are two languages in common use: Java and Objective-C. This document describes the Java bridge, a technology from Apple that makes communication between these two languages possible. The first section, ÒIntroduction,Ó gives a brief overview of the bridgeÕs capabilities. For a technical overview of the bridge, see ÒHow the Bridge WorksÓ (page 2). To learn how to expose your Objective-C code to Java, see ÒWrapping Objective-C FrameworksÓ (page 9). If you want to write Java code that references Objective-C classes, see ÒUsing Java-Wrapped Objective-C ClassesÓ (page 6). If you are writing Objective-C code that references Java classes, read ÒUsing Java from Objective-CÓ (page 5). Introduction The original OpenStep system developed by NeXT Software contained a number of object-oriented frameworks written in the Objective-C language. Most developers who used these frameworks wrote their code in Objective-C. In recent years, the number of developers writing Java code has increased dramatically. For the benefit of these programmers, Apple Computer has provided Java APIs for these frameworks: Foundation Kit, AppKit, WebObjects, and Enterprise Objects. They were made possible by using techniques described later in Introduction 1 Using the Java Bridge this document. You can use these same techniques to expose your own Objective-C frameworks to Java code. Java and Objective-C are both object-oriented languages, and they have enough similarities that communication between the two is possible. However, there are some differences between the two languages that you need to be aware of in order to use the bridge effectively.
    [Show full text]
  • GCC Toolchain Eclipse Setup Guide
    !"#$ % '#((#()*!+,-.#)/$01234 GCC Toolchain Eclipse Setup Guide WP0001 Version 5 September 23, 2020 Copyright © 2017-2020 JBLopen Inc. All rights reserved. No part of this document and any associated software may be reproduced, distributed or transmitted in any form or by any means without the prior written consent of JBLopen Inc. Disclaimer While JBLopen Inc. has made every attempt to ensure the accuracy of the information contained in this publication, JBLopen Inc. cannot warrant the accuracy of completeness of such information. JBLopen Inc. may change, add or remove any content in this publication at any time without notice. All the information contained in this publication as well as any associated material, including software, scripts, and examples are provided “as is”. JBLopen Inc. makes no express or implied warranty of any kind, including warranty of merchantability, noninfringement of intellectual property, or fitness for a particular purpose. In no event shall JBLopen Inc. be held liable for any damage resulting from the use or inability to use the information contained therein or any other associated material. Trademark JBLopen, the JBLopen logo, TREEspanTM and BASEplatformTM are trademarks of JBLopen Inc. All other trademarks are trademarks or registered trademarks of their respective owners. Contents 1 Overview 1 1.1 About Eclipse ............................................. 1 2 Eclipse Setup Guide (Windows) 2 2.1 MSYS2 Installation .......................................... 2 2.2 Eclipse Installation .......................................... 11 2.3 Toolchain Installation ......................................... 16 2.4 Environment Variable Setup ..................................... 17 2.4.1 PATH Environnement Variable Setup ........................... 17 3 Eclipse Setup Guide (Linux) 22 3.1 Eclipse Installation .......................................... 22 3.2 Toolchain Installation ......................................... 27 3.3 GNU Make Installation .......................................
    [Show full text]