0 / 0 / 1
Регистрация: 07.05.2013
Сообщений: 83
|
|
1 | |
О чем задача?18.07.2013, 01:31. Показов 1943. Ответов 13
Метки нет (Все метки)
Не пойму некоторых начальных условий задачи.
Особенно пунктов 40-43 с ветвлениями. Допустим А больше В, разница меньше 0 и выполняется комманда 4207 - заносится результат (А-В) в адресс 07. А дальше не пойму. Как проверить больше А или нет. Просто использовать "если"? Можно обратиться в ячейку 07 и вывести на экран - увидел что значение отрицательное и тогда, что-то исполняешь? Как найти макс число не пойму? И думаю это 1е не пойму по этой задаче
0
|
18.07.2013, 01:31 | |
Ответы с готовыми решениями:
13
Задача math, не могу понять в чем ошибки в чем ошибка? Задача на "положение улитки" в чем ошибка? задача на "сортировку массива" Рекурсия: определите подмножество данных чисел, дающих сумму меньше, чем Z и с количеством членов большим чем K |
0 / 0 / 1
Регистрация: 07.05.2013
Сообщений: 83
|
||||||
18.07.2013, 02:03 [ТС] | 2 | |||||
Это набросок без пунктов 40-43
Условия задачи(она длинная очень - поэтому я не особо пойму как без картинок ее описать): In the next several problems, we take a temporary diversion away from the world of high-level-language programming. We “peel open” a computer and look at its internal structure. We introduce machine-language programming and write several machine-language programs. To make this an especially valuable experience, we then build a computer (using software-based simulation) on which you can execute your machine-language programs! 8.18 (Machine-Language Programming) Let’s create a computer we’ll call the Simpletron. As its name implies, it’s a simple machine, but, as we’ll soon see, it’s a powerful one as well. The Simpletron runs programs written in the only language it directly understands, that is, Simpletron Machine Language, or SML for short. The Simpletron contains an accumulator—a “special register” in which information is put before the Simpletron uses that information in calculations or examines it in various ways. All information in the Simpletron is handled in terms of words. A word is a signed four-digit decimal number, such as +3364, -1293, +0007, -0001, etc. The Simpletron is equipped with a 100-word memory, and these words are referenced by their location numbers 00, 01, …, 99. Before running an SML program, we must load, or place, the program into memory. The first instruction (or statement) of every SML program is always placed in location 00. The simulator will start executing at this location. Each instruction written in SML occupies one word of the Simpletron’s memory; thus, instructions are signed four-digit decimal numbers. Assume that the sign of an SML instruction is always plus, but the sign of a data word may be either plus or minus. Each location in the SimSpecial Section: Building Your Own Computer 373 pletron’s memory may contain an instruction, a data value used by a program or an unused (and hence undefined) area of memory. The first two digits of each SML instruction are the operation code that specifies the operation to be performed. SML operation codes are shown in Fig. 8.23. The last two digits of an SML instruction are the operand—the address of the memory location containing the word to which the operation applies. Now let’s consider two simple SML programs. The first (Fig. 8.24) reads two numbers from the keyboard and computes and prints their sum. The instruction +1007 reads the first number from the keyboard and places it into location 07 (which has been initialized to zero). Instruction +1008 reads the next number into location 08. The load instruction, +2007, places (copies) the first Operation code Meaning Input/output operations const int READ = 10; Read a word from the keyboard into a specific location in memory. const int WRITE = 11; Write a word from a specific location in memory to the screen. Load and store operations const int LOAD = 20; Load a word from a specific location in memory into the accumulator. const int STORE = 21; Store a word from the accumulator into a specific location in memory. Arithmetic operations const int ADD = 30; Add a word from a specific location in memory to the word in the accumulator (leave result in accumulator). const int SUBTRACT = 31; Subtract a word from a specific location in memory from the word in the accumulator (leave result in accumulator). const int DIVIDE = 32; Divide a word from a specific location in memory into the word in the accumulator (leave result in accumulator). const int MULTIPLY = 33; Multiply a word from a specific location in memory by the word in the accumulator (leave result in accumulator). Transfer-of-control operations const int BRANCH = 40; Branch to a specific location in memory. const int BRANCHNEG = 41; Branch to a specific location in memory if the accumulator is negative. const int BRANCHZERO = 42; Branch to a specific location in memory if the accumulator is zero. const int HALT = 43; Halt—the program has completed its task. Fig. 8.23 | Simpletron Machine Language (SML) operation codes. 374 Chapter 8 Pointers number into the accumulator, and the add instruction, +3008, adds the second number to the number in the accumulator. All SML arithmetic instructions leave their results in the accumulator. The store instruction, +2109, places (copies) the result back into memory location 09. Then the write instruction, +1109, takes the number and prints it (as a signed four-digit decimal number). The halt instruction, +4300, terminates execution. The SML program in Fig. 8.25 reads two numbers from the keyboard, then determines and prints the larger value. Note the use of the instruction +4107 as a conditional transfer of control, much the same as C++’s if statement. Now write SML programs to accomplish each of the following tasks: Location Number Instruction 00 +1007 (Read A) 01 +1008 (Read B) 02 +2007 (Load A) 03 +3008 (Add B) 04 +2109 (Store C) 05 +1109 (Write C) 06 +4300 (Halt) 07 +0000 (Variable A) 08 +0000 (Variable B) 09 +0000 (Result C) Fig. 8.24 | SML Example 1. Location Number Instruction 00 +1009 (Read A) 01 +1010 (Read B) 02 +2009 (Load A) 03 +3110 (Subtract B) 04 +4107 (Branch negative to 07) 05 +1109 (Write A) 06 +4300 (Halt) 07 +1110 (Write B) 08 +4300 (Halt) 09 +0000 (Variable A) 10 +0000 (Variable B) Fig. 8.25 | SML Example 2. Special Section: Building Your Own Computer 375 a) Use a sentinel-controlled loop to read positive numbers and compute and print their sum. Terminate input when a negative number is entered. b) Use a counter-controlled loop to read seven numbers, some positive and some negative, and compute and print their average. c) Read a series of numbers, and determine and print the largest number. The first number read indicates how many numbers should be processed. 8.19 (Computer Simulator) It may at first seem outrageous, but in this problem you are going to build your own computer. No, you won’t be soldering components together. Rather, you’ll use the powerful technique of software-based simulation to create a software model of the Simpletron. Your Simpletron simulator will turn the computer you are using into a Simpletron, and you actually will be able to run, test and debug the SML programs you wrote in Exercise 8.18. When you run your Simpletron simulator, it should begin by printing *** Welcome to Simpletron! *** *** Please enter your program one instruction *** *** (or data word) at a time. I will type the *** *** location number and a question mark (?). *** *** You then type the word for that location. *** *** Type the sentinel -99999 to stop entering *** *** your program. *** Your program should simulate the Simpletron’s memory with a single-subscripted, 100-element array memory. Now assume that the simulator is running, and let’s examine the dialog as we enter the program of the second example of Exercise 8.18: 00 ? +1009 01 ? +1010 02 ? +2009 03 ? +3110 04 ? +4107 05 ? +1109 06 ? +4300 07 ? +1110 08 ? +4300 09 ? +0000 10 ? +0000 11 ? -99999 *** Program loading completed *** *** Program execution begins *** The numbers to the right of each ? in the preceding dialog represent the SML program instructions input by the user. The SML program has now been placed (or loaded) into array memory. Now the Simpletron executes your SML program. Execution begins with the instruction in location 00 and, like C++, continues sequentially, unless directed to some other part of the program by a transfer of control. Use variable accumulator to represent the accumulator register. Use variable instructionCounter to keep track of the location in memory that contains the instruction being performed. Use variable operationCode to indicate the operation currently being performed (i.e., the left two digits of the instruction word). Use variable operand to indicate the memory location on which the current instruction operates. Thus, operand is the rightmost two digits of the instruction currently being performed. Do not execute instructions directly from memory. Rather, transfer the next instruction to be performed from memory to a variable called instructionRegister. Then “pick off ” the left two digits and place them in operationCode, and “pick off ” the right two digits and place them in operand. When Simpletron begins execution, the special registers are all initialized to zero. 376 Chapter 8 Pointers Now let’s “walk through” the execution of the first SML instruction, +1009 in memory location 00. This is called an instruction execution cycle. The instructionCounter tells us the location of the next instruction to be performed. We fetch the contents of that location from memory by using the C++ statement instructionRegister = memory[ instructionCounter ]; The operation code and operand are extracted from the instruction register by the statements operationCode = instructionRegister / 100; operand = instructionRegister % 100; Now, the Simpletron must determine that the operation code is actually a read (versus a write, a load, etc.). A switch differentiates among the 12 operations of SML. In the switch statement, the behavior of various SML instructions is simulated as shown in Fig. 8.26 (we leave the others to you). The halt instruction also causes the Simpletron to print the name and contents of each register, as well as the complete contents of memory. Such a printout is often called a register and memory dump. To help you program your dump function, a sample dump format is shown in Fig. 8.27. Note that a dump after executing a Simpletron program would show the actual values of instructions and data values at the moment execution terminated. To format numbers with their sign as shown in the dump, use stream manipulator showpos. To disable the display of the sign, use stream manipulator noshowpos. For numbers that have fewer than four digits, you can format numbers with leading zeros between the sign and the value by using the following statement before outputting the value: cout << setfill( '0' ) << internal; read: cin >> memory[ operand ]; load: accumulator = memory[ operand ]; add: accumulator += memory[ operand ]; branch: We’ll discuss the branch instructions shortly. halt: This instruction prints the message *** Simpletron execution terminated *** Fig. 8.26 | Behavior of SML instructions. REGISTERS: accumulator +0000 instructionCounter 00 instructionRegister +0000 operationCode 00 operand 00 MEMORY: 0 1 2 3 4 5 6 7 8 9 0 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 10 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 20 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 30 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 40 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 50 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 60 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 70 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 80 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 90 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 +0000 Fig. 8.27 | A sample register and memory dump. Special Section: Building Your Own Computer 377 Parameterized stream manipulator setfill (from header <iomanip>) specifies the fill character that will appear between the sign and the value when a number is displayed with a field width of five characters but does not have four digits. (One position in the field width is reserved for the sign.) Stream manipulator internal indicates that the fill characters should appear between the sign and the numeric value . Let’s proceed with the execution of our program’s first instruction—+1009 in location 00. As we’ve indicated, the switch statement simulates this by performing the C++ statement cin >> memory[ operand ]; A question mark (?) should be displayed on the screen before the cin statement executes to prompt the user for input. The Simpletron waits for the user to type a value and press the Enter key. The value is then read into location 09. At this point, simulation of the first instruction is complete. All that remains is to prepare the Simpletron to execute the next instruction. The instruction just performed was not a transfer of control, so we need merely increment the instruction counter register as follows: ++instructionCounter; This completes the simulated execution of the first instruction. The entire process (i.e., the instruction execution cycle) begins anew with the fetch of the next instruction to execute. Now let’s consider how to simulate the branching instructions (i.e., the transfers of control). All we need to do is adjust the value in the instructionCounter appropriately. Therefore, the unconditional branch instruction (40) is simulated in the switch as instructionCounter = operand; The conditional “branch if accumulator is zero” instruction is simulated as if ( accumulator == 0 ) instructionCounter = operand; At this point, you should implement your Simpletron simulator and run each of the SML programs you wrote in Exercise 8.18. The variables that represent the Simpletron simulator’s memory and registers should be defined in main and passed to other functions by value or by reference as appropriate. Your simulator should check for various types of errors. During the program loading phase, for example, each number the user types into the Simpletron’s memory must be in the range -9999 to +9999. Your simulator should use a while loop to test that each number entered is in this range and, if not, keep prompting the user to reenter the number until the user enters a correct number. During the execution phase, your simulator should check for various serious errors, such as attempts to divide by zero, attempts to execute invalid operation codes, accumulator overflows (i.e., arithmetic operations resulting in values larger than +9999 or smaller than -9999) and the like. Such serious errors are called fatal errors. When a fatal error is detected, your simulator should print an error message such as *** Attempt to divide by zero *** *** Simpletron execution abnormally terminated *** and should print a full register and memory dump in the format we’ve discussed previously. This will help the user locate the error in the program. 8.20 (Project: Modifications to the Simpletron Simulator) In Exercise 8.19, you wrote a software simulation of a computer that executes programs written in Simpletron Machine Language (SML). In this exercise, we propose several modifications and enhancements to the Simpletron Simulator. In Exercises 20.31–20.35, we propose building a compiler that converts programs written in a highlevel programming language (a variation of BASIC) to SML. Some of the following modifications
0
|
3 / 3 / 1
Регистрация: 19.02.2014
Сообщений: 115
|
|
16.04.2015, 16:42 | 3 |
А может кто пояснить на пальцах,чего вообще требуется.Дошел до этой задачи,нифига не могу вкурить че нужно вообще.Какой принцип работы программа должна выполнять?Вот допустим осуществляется ввод команд,каждая команда должна записываться в массив?Если так,дальше что как ввод закончен?Она должна потом просто по массиву проходить находить каждую команду обрабатывать(в switche)?И если под командой имеется ввиду ввод числа,должно выдать ввод числа?Не могу сообразить куда допустим помещать те же введенные числа и прочее.Или значения просто присваивать переменным и потом вызывать? Поиском что-то про эту задачу вообще ничего не нашел. Условие на картинке
0
|
223 / 37 / 4
Регистрация: 18.11.2012
Сообщений: 1,502
|
|
29.11.2016, 21:39 | 4 |
Вот и я дошёл до этой задачи и тоже ни фига не пойму что к чему. Что значит отойдём от ЯВУ и познакомиться с машинным языком, хорошо, тогда ассемблер в помощь а, писать то на каком языке?! Значит нужно делать так, как я понял условие, вводим число nn - это код операции, следующие nn - это адрес памяти, значит, он не может превышать 99 далее нужно ещё данные куда-то прикрутить это может выглядеть примерно так: nn - код операции, nn - значение адреса, mmmm - некое значение данных, так? А может нужно вводить команды, вроде, READ, WRITE? не понятно. А аккумулятор - это что обращаться к регистру AX нужно или выделить память и назвать переменную AX или как-то так? Почему-то вопросов больше, чем ответов.
0
|
59 / 54 / 34
Регистрация: 18.04.2014
Сообщений: 122
|
||||||
29.11.2016, 22:56 | 5 | |||||
Liss29, Не знаю о какой книги идет речь, и что требуется в ней, но из 3 скриншота видно, что требуется написать программу на этом выдуманном языке программирования, как показано на примерах на втором скриншоте.
Да так. Полагаю на С++ нужно реализоавть нечто вроде компьютера, он идет по "памяти начиная с адреса 0" (по массиву в 100 элементов типа инт) и выполняет действия в соответствии с командами записанными в этих ячейках. Полагаю на начальном этапе можно реализоать просто "выполнение команд из памяти" как я описал выше. В дальнейшем можно сделать своего рода "компилятор" с этого языка в машинный код. Т.е. в текстовом файле у вас будет что-то вроде: Код
READ 07 READ 08 LOAD 07 ADD 08 ....
0
|
223 / 37 / 4
Регистрация: 18.11.2012
Сообщений: 1,502
|
|
30.11.2016, 05:21 | 6 |
Компилятор не требую, пока что, тфу тфу дело в том, и на скринах это видно, что команды вводятся цифрами 1007, 1008... поэтому и решил уточнить. Значит моё понимание задачи верно, тогда можно и попробовать написать. Тут вот ещё что: Хочу записать данные в память, например, 1007 тогда это седьмая ячейка памяти получается, команда и адрес весят "слово" и данные столько же, тогда это пулучается надо записать данные в адрес начиная с 28 значения в памяти. Обращаться к памяти для Записи/чтения удобно было бы так, на мой взгляд, n - адрес ячейки, той же 07, мы его n * 4 = addres; думаю, это правильно, хотя тогда уже обращение к ячейке 26 выходит за пределы моего адресного простанства, а в условии написано, что надо обращаться к памяти начиная с 00, 01, 02,..,99 значит тут я тоже неправ. Попробую,если что-либо будет не понятно буду спрашивать.
0
|
223 / 37 / 4
Регистрация: 18.11.2012
Сообщений: 1,502
|
||||||
20.12.2016, 21:23 | 7 | |||||
Такой вопрос, если в задаче указан массиа типа int , то как туда в одном слове впихнуть знак, кторый имеет тип char и четыре цифры, которые имеют, соответственно, тип int? При вводе знака и чисел, в массив попадают, только, числа int, без знака, а надо, как я понял, массив и 100 таких вот слов, которые имеют вид +1234, -4321 как-то так.
Пока дошёл только до этого, набросок так сказать)
0
|
59 / 54 / 34
Регистрация: 18.04.2014
Сообщений: 122
|
||||||
20.12.2016, 21:57 | 8 | |||||
Liss29,
Код
Введите отрицательное число:-4321 Введено i: -4321 i + 2: -4319
1
|
223 / 37 / 4
Регистрация: 18.11.2012
Сообщений: 1,502
|
|
20.12.2016, 22:15 | 9 |
Mathist
Хмм с минусом вводится, и в память (массив) помещается тоже с минусом, а сплюсом не хотит, ладно, буду думать дальше, теперь симулятор компьютера Simpletron-а надо написать.)
0
|
223 / 37 / 4
Регистрация: 18.11.2012
Сообщений: 1,502
|
|||||||||||
23.12.2016, 06:36 | 10 | ||||||||||
//Симулятор
Кликните здесь для просмотра всего текста
И мои варианты решения задач из 8.18 Кликните здесь для просмотра всего текста
0
|
8739 / 4317 / 960
Регистрация: 15.11.2014
Сообщений: 9,760
|
|
23.12.2016, 11:17 | 11 |
задачу не читал. но очевидно жеж - интерпретатор машинного кода.
0
|
223 / 37 / 4
Регистрация: 18.11.2012
Сообщений: 1,502
|
|
23.12.2016, 20:22 | 12 |
Задача полностью описана во втором посте.
И... это к чему сказано
0
|
Maxim Prishchepa
|
23.12.2016, 20:25
#13
|
Не по теме: too many bukv
0
|
Liss29
|
23.12.2016, 20:36
О чем задача?
#14
|
Не по теме: а что поделать)
0
|
23.12.2016, 20:36 | |
Задача на рекурсию (в чем ошибка?) В чем заключается задача анализа схемы? Найти сумму чётных элементов матрицы, исключая максимальный и минимальный, заменить ей угловые элементы Есть задача, подскажите на чем проще писать? Искать еще темы с ответами Или воспользуйтесь поиском по форуму: |