Форум программистов, компьютерный форум, киберфорум
С++ для начинающих
Войти
Регистрация
Восстановить пароль
Карта форума Темы раздела Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.73/11: Рейтинг темы: голосов - 11, средняя оценка - 4.73
0 / 0 / 1
Регистрация: 07.05.2013
Сообщений: 83
1

О чем задача?

18.07.2013, 01:31. Показов 1943. Ответов 13
Метки нет (Все метки)

Author24 — интернет-сервис помощи студентам
Не пойму некоторых начальных условий задачи.
Особенно пунктов 40-43 с ветвлениями.
Допустим А больше В, разница меньше 0 и выполняется комманда 4207 - заносится результат (А-В) в адресс 07. А дальше не пойму. Как проверить больше А или нет. Просто использовать "если"? Можно обратиться в ячейку 07 и вывести на экран - увидел что значение отрицательное и тогда, что-то исполняешь? Как найти макс число не пойму?
И думаю это 1е не пойму по этой задаче
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
18.07.2013, 01:31
Ответы с готовыми решениями:

Задача math, не могу понять в чем ошибки
Приветствую, в универе задали сделать задачку, написать пример с парой переменных. Записать этот...

в чем ошибка? Задача на "положение улитки"
помогите пожалуйста! в чем ошибка в даном коде? Каждый солнечный день улитка, сидящая на дереве,...

в чем ошибка? задача на "сортировку массива"
Подскажите в чем ошибка в коде. Я должен отсортировать массив по убыванию элементов. #include...

Рекурсия: определите подмножество данных чисел, дающих сумму меньше, чем Z и с количеством членов большим чем K
имеется n различных натуральных чисел. определите подмножество данных чисел, дающих сумму меньше,...

13
0 / 0 / 1
Регистрация: 07.05.2013
Сообщений: 83
18.07.2013, 02:03  [ТС] 2
Это набросок без пунктов 40-43
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
// Simpletron.cpp : Defines the entry point for the console application.
//
 
#include "stdafx.h"
#include <iostream>
#include "conio.h"
 
using namespace std;
 
int iInputInstruction();
 
int _tmain(int argc, _TCHAR* argv[])
{
    const int iSize = 100;
    bool b = true; //Print User terminated or autoterminated with error
    int iMemoryStack[iSize]={}; // Memory
    int iInstructionRegister;
    int iInstructionCounter = 0;
    int iOperationCode;
    int iOperator;
    int iAccamulator;
    while (((iInstructionRegister>-10000 && iInstructionRegister<-999) || (iInstructionRegister<10000 && iInstructionRegister>999)) && b) //4значное число
    {
    iInstructionRegister = memory [iInstructionCounter];
    iOperationCode = iInstructionRegister/100;
    iOperator = iInstructionRegister%100;
    switch (iOperationCode)
    {
    case 10:
        cin >> iMemoryStack[iOperator];
        break;
    case 11:
        cout << "Value in cell " << iOperator << " is: " << iMemoryStack[iOperator] << endl;
        break;
    case 20:
        iAccamulator = iMemoryStack[iOperator];
        break;
    case 21:
        iMemoryStack[iOperator] = iAccamulator;
        break;
    case 30:
        iAccamulator += iMemoryStack[iOperator];
        break;
    case 31:
        iAccamulator -= iMemoryStack[iOperator];
        break;
    case 32:
        iAccamulator *= iMemoryStack[iOperator];
        break;
    case 33:
        iAccamulator /= iMemoryStack[iOperator];
        break;
    case 40:
        iInstructionCounter = iOperator;
        break;
    case 41:
        if ( iAccumulator < 0 )
            iInstructionCounter = iOperator;
        break;
    case 42:
        if ( iAccumulator == 0 )
            iInstructionCounter = iOperator;
        break;
    case 43:
        b = false;
        cout << "*** Simpletron execution terminated ***" << endl;
        break;
    default:
        cout << "You've input insence Code!" << endl;
        break;
    }
    iInstructionCounter++;
    }
    _getch();
    return 0;
}
 
int iInputInstruction()
{
    int I;
    while (!(cin >> I))
    {
        cin.clear();
        cin.ignore(50, '\n');
        cout << "Please enter right value!" << endl;
    }
    return I;
}
Добавлено через 22 минуты
Условия задачи(она длинная очень - поэтому я не особо пойму как без картинок ее описать):
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 скриншота видно, что требуется написать программу на этом выдуманном языке программирования, как показано на примерах на втором скриншоте.
Цитата Сообщение от Liss29 Посмотреть сообщение
Значит нужно делать так, как я понял условие, вводим число nn - это код операции, следующие nn - это адрес памяти, значит, он не может превышать 99 далее нужно ещё данные куда-то прикрутить это может выглядеть примерно так: nn - код операции, nn - значение адреса, mmmm - некое значение данных, так?
Да так. Полагаю на С++ нужно реализоавть нечто вроде компьютера, он идет по "памяти начиная с адреса 0" (по массиву в 100 элементов типа инт) и выполняет действия в соответствии с командами записанными в этих ячейках.

Цитата Сообщение от Liss29 Посмотреть сообщение
А может нужно вводить команды, вроде, READ, WRITE?
Полагаю на начальном этапе можно реализоать просто "выполнение команд из памяти" как я описал выше. В дальнейшем можно сделать своего рода "компилятор" с этого языка в машинный код. Т.е. в текстовом файле у вас будет что-то вроде:
Код
    READ 07
    READ 08
    LOAD 07
    ADD 08
    ....
Откомпилировав этот "код" (заменив команды на их цифровые представления) и "прошив" (записав в массив в вашей программе) свой компьютер вы уже сможете использовать код написанный на первом этапе для его проверки. Вот пример заполненного массива в вашей программе:
C++
1
2
3
4
5
6
int array[100];
a[0] = 1007;
a[1] = 1008;
a[2] = 2007;
a[3] = 3008;
//...
Цитата Сообщение от Liss29 Посмотреть сообщение
А аккумулятор - это что обращаться к регистру AX нужно или выделить память и назвать переменную AX или как-то так?
Под аккумулятор выделите переменную. К реальному железу задание отношения не имеет. Ваша основная задача создать эмуляцию работы этого выдуманного компьютера в соответствии с описанными правилами.
0
223 / 37 / 4
Регистрация: 18.11.2012
Сообщений: 1,502
30.11.2016, 05:21 6
Не знаю о какой книги идет речь
Дейтелы Как программировать на C++. Всё тоже самое, что и на скрине выше.

Компилятор не требую, пока что, тфу тфу дело в том, и на скринах это видно, что команды вводятся цифрами 1007, 1008...
поэтому и решил уточнить. Значит моё понимание задачи верно, тогда можно и попробовать написать.

Тут вот ещё что:
Словом будем здесь называть десятичное число из четырех цифр со знаком, например, +3364, -1293,
+0007, -0001 и т.д.
Мы договоримся о том, что команды SML всегда имеют знак плюс,тогда как знак слова данных может быть либо плюсом, либо минусом.
Интересно зачем все эти плюсы минусы, явно, что это не арифметика, для красоты что ли. Например, зачем они в данных нужны, для команды перехода?! Мне показалось, что если при вычитании или делении образовалось число отрицательное и я делаю проверку на то будет число положительным или отрецательным, тогда переходим в одном случае, если положительное число, иначе если число отрицательно, но похоже не так. Видимо минус именно для того и вставляется?! Может я ошибаюсь...

Хочу записать данные в память, например, 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 как-то так.

Пока дошёл только до этого, набросок так сказать)
C++
1
2
3
4
5
6
7
8
9
10
11
12
char sign;
int wordDate;
for(int i = 0; i < 100; i++)
    {
        for(int j = i + i; j < i*2 + 2; j++)
        {
            cin >> sign;
            s.memory[j++] = static_cast<int>(sign);
            cin >> wordDate;
            s.memory[j] = wordDate;
        }
    }
0
59 / 54 / 34
Регистрация: 18.04.2014
Сообщений: 122
20.12.2016, 21:57 8
Liss29,
C++
1
2
3
4
5
6
7
8
9
10
#include <iostream>
 
int main() {
 
    int i;
    std::cout << "Введите отрицательное число:";
    std::cin >> i;
    std::cout << "Введено i: " << i;
    std::cout << "\ni + 2: " << i + 2;
}
Вывод
Код
Введите отрицательное число:-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
//Симулятор
Кликните здесь для просмотра всего текста
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
#include <iostream>
#include <iomanip>
//#include <windows.h>
//#include <stdio.h> 
//#include "TEXT.h"
 
 
struct SIMPLETRON
{
    int memory[100];
    int acumulator; //??????????
    int instructionCounter;//????? ???????? ??????????? ???????
    int operationCode; //??? ???????? ??? ??????? ???????????
                       //???????.
    int operand; //????? ???????? ?????? ??????????? ??????? 
    int instructionRegister; //????????????? ??????? ??? 
                             //???????? ??????????? ??????? 
};
 
 
void runing(SIMPLETRON *sim);
void DUMP(SIMPLETRON *sim);
enum OPERATION{READ = 10, WRITE = 11, LOAD = 20, STORE = 21, ADD = 30, SUBTRACT = 31, DIVIDE = 32, MULTIPLY = 33, BRANCH = 40, BRANCHNEG = 41, BRANCHZERO = 42, HALT = 43};
void startInfo();
using namespace std;
int main()
{
    OPERATION operation = READ;
    SIMPLETRON s;
 
    for(int x = 0; x < 100; x++)
    {
        s.memory[x] = +0000;
    }
 
    //int wordDate;
    int counter = 0;
    //==================================================================================
    startInfo();
    int wordDate;
 
    while(wordDate != -99999)
    {
        if(counter < 10)
        {
            cout << "0" << counter << "?" << ' ';
            cin >> wordDate;
            if((wordDate < -9999 || wordDate > 9999) && wordDate != -99999)
            {
                do 
                {
                    cout << "0" << counter << "?" << ' ';
                    cin >> wordDate;
                }
                while((wordDate < -9999 || wordDate > 9999) && wordDate != -99999);
                s.memory[counter++] = wordDate;
                //cout << endl;
            }
            else if(wordDate == - 99999)
            {
                break;
            }
            else 
            {
                s.memory[counter++] = wordDate;
            }
        }
        else
        {
            cout << counter << "?" << ' ';
            cin >> wordDate;
            if((wordDate < -9999 || wordDate > 9999) && wordDate != -99999)
            {
                do 
                {
                    cout << counter << "?" << ' ';
                    cin >> wordDate;
                }
                while((wordDate < -9999 || wordDate > 9999) && wordDate != -99999);
                s.memory[counter++] = wordDate;
                //cout << endl;
            }
            else if(wordDate == -99999)
            {
                break;
            }
            else 
            {
                s.memory[counter++] = wordDate;
            }
        }
    }
    cout << "*** " << "Загрузка программы завершена" << " ***" << endl;
    cout << "*** " << "Начинаю выполнение программы" << " ***" << endl;
 
    runing(&s);
    //==================================================================================
    
    cout << endl;
    return 0;
}
 
 
void runing(SIMPLETRON *sim)
{
    bool status = true;
    sim->acumulator = 00;
    sim->instructionCounter = 00;
    sim->instructionRegister = 00;
    sim->operand = 00;
    sim->operationCode = 00;
    while(status)
    {
        sim->instructionRegister = sim->memory[sim->instructionCounter];
        sim->operationCode = sim->instructionRegister / 100;
        sim->operand = sim->instructionRegister % 100;
        switch(sim->operationCode)
        {
            case READ:
                cout << "? ";
                cin >> sim->memory[sim->operand];
                sim->instructionCounter++;
            break; 
            
            case WRITE:
                cout << "=====================" << endl;
                cout << "|" << "Result = " << showpos << sim->memory[sim->operand] << "|" << endl;
                cout << "=====================" << endl;
                sim->instructionCounter++;
            break;
            
            case LOAD: 
                sim->acumulator = sim->memory[sim->operand];            
                sim->instructionCounter++; 
            break;
            
            case STORE: 
                sim->memory[sim->operand] = sim->acumulator; 
                sim->instructionCounter++;
            break;
            
            case ADD:
                sim->acumulator += sim->memory[sim->operand];
                if(sim->acumulator > 9999)
                {
                    sim->acumulator = 0;
                    cout << "*** " << "В результате вычислений произошло переполнение акумулятора" << " ***" << endl;
                    cout << "*** " << "Симплетрон аварийно завершил выполнение программы" << " ***" << endl;
                    DUMP(sim);
                    status = false;
                    break;
                }
                else 
                    sim->instructionCounter++;
                    break;
                
            case SUBTRACT: 
                sim->acumulator -= sim->memory[sim->operand];
                sim->instructionCounter++;
                if(sim->acumulator < -9999)
                {
                    sim->acumulator = 0;
                    cout << "*** " << "В результате вычислений произошло переполнение акумулятора" << " ***" << endl;
                    cout << "*** " << "Симплетрон аварийно завершил выполнение программы" << " ***" << endl;
                    DUMP(sim);
                    status = false;
                    break; 
                }
                else 
                {
                    break;
                }
                
            case DIVIDE:
                if(sim->memory[sim->operand] == 0)
                {
                    cout << "*** " << "Ошибка: попытка деления на нуль!" << " ***" << endl;
                    cout << "*** " << "Симплетрон аварийно завершил выполнение программы" << " ***" << endl;
                    DUMP(sim);
                    status = false;
                    break;
                }
                else 
                {
                    sim->acumulator /= sim->memory[sim->operand];
                    sim->instructionCounter++;
                    break;
                }
            
            case MULTIPLY:
                sim->acumulator *= sim->memory[sim->operand];
                sim->instructionCounter++;
                if(sim->acumulator > 9999)
                {
                    cerr << "*** " << "Результат операции умножения превосходит допустимый предел" << " ****" << endl;
                    cerr << "*** " << "Симплетрон аварийно завершил выполнение прогаммы" << " ***" << endl;
                    DUMP(sim);
                    sim->acumulator = 0;
                    status = false;
                    break;
                }
                else 
                {
                    break;
                }
            
            case BRANCH:
                sim->instructionCounter = sim->operand;
            break;
            
            case BRANCHNEG:
                if(sim->acumulator < 0)
                {
                    sim->instructionCounter = sim->operand;
                    break;
                }
                else 
                {
                    sim->instructionCounter++;
                    break;
                }
                
            case BRANCHZERO:
                if(sim->acumulator == 0)
                {
                    sim->instructionCounter = sim->operand;
                    break;
                }
                else
                {
                    sim->instructionCounter++;
                    break;
                }
            
            case HALT:
                status = false;
                cout << "*** " << "Симплетрон закончил свои вычисления" << " ***" << endl;
                cout << endl;
                DUMP(sim);
                break;
            default:
                cerr << "Неправильный код операции" << endl;
                DUMP(sim);
                status = false;
                break;
        }
    }
}
 
void DUMP(SIMPLETRON *sim)
{
    cout << "РЕГИСТРЫ:" << endl;
    cout << "acumulator:          " << sim->acumulator << endl;
    cout << "instructionCounter:  " << sim->instructionCounter << endl;
    cout << "instructionRegister: " << sim->instructionRegister << endl;
    cout << "operationCode:       " << sim->operationCode << endl;
    cout << "operand:             " << sim->operand << endl;
    cout << endl;
    cout << "ПАМЯТЬ:" << endl;
//============================================================= 
    cout << "  ";
    for(int row = 0; row < 10; row++)
    {
        cout << setw(7) << row;
    }
    cout << endl;
 
    for(int n = 0; n < 100; n += 10)
    {
        if(n == 0)
            cout << ' ' << noshowpos << n;
        else 
            cout << noshowpos << n;
        for(int m = n; m < n + 10; m++)
        {
            cout << "  ";
            if(sim->memory[m] == 0)
            {
                cout << setw(5) << showpos << right << "+0000";
            }
            else
            {
                cout << setw(5) << showpos << right << sim->memory[m];
            }
        }
        cout << endl;
    }
}
 
void startInfo()
{
    cout << "*** " << "Симплетрон приветствует вас!" << " ***" << endl;
    cout << "*** " << "Пожалуйста, введите вашу программу, по одной команде" << " ***" << endl;
    cout << "*** " << "(или слову данных) за раз. Я буду выводить в качестве" << " ***" << endl;
    cout << "*** " << "подсказки текущий адрес и знак вопроса(?). Введённое" << " ***" << endl;
    cout << "*** " <<  "вами слово будет размещено по указанному адресу. Для" << " ***" << endl;
    cout << "*** " << "прекращения ввода программы введите число  -99999" << " ***" << endl;
}


И мои варианты решения задач из 8.18
Кликните здесь для просмотра всего текста
C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
+10 09
+10 10
+20 10
+41 07
+30 09
+21 09
+40 01 
+11 09
+43 00
//=================
+10 21  //первое число 
+10 22  //счётчик
+10 23  //число для уменьшения счётчика
 
+20 22
+21 25 //сохранит по этому адресу значение счётчика, которе    //  используется для вычисления среднего значения
//+20 21
+31 23
 
+10 24  //второе число
 
+42 15 
+21 22 
+20 24 
+30 21 
+21 21 
+20 22
+31 23
+40 06  //цикл 
//+10 24    //число для вычисления среднего введённых чисел
+20 21
+32 25
+21 21
+11 21
+43 00 
 
//========================
+10 25 //количество чисел, которые нужно обработать
+20 25
+21 26 //сохраним и используем как счётчик 
+10 27 //число с помощью которого уменьшаем счётчик(например 1)
 
+20 26
+31 27 //уменьшить счётчик на 1 
 
+42 23 //если счетчик количества ввод символ 0 то уходим на 20
+21 26 //сохраним счётчик  
+10 28 //второе число
+20 25 //в акумулятор первое число
+21 29 //временно сохраним перове число т.к. результат 
       //вычисления изменить первоначальное значение
+31 28
+41 18
+20 29 //восстановим сохранённое значение числа 
+21 25 
+20 26
+31 27  //уменьшим счетчик
+40 06
  
+20 28 
+21 25
+20 26 //уменьшим счётчик 
+31 27
+40 06 
 
+11 25 
+43 00
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
Цитата Сообщение от hoggy Посмотреть сообщение
задачу не читал
Задача полностью описана во втором посте.
Цитата Сообщение от hoggy Посмотреть сообщение
но очевидно жеж - интерпретатор машинного кода.
И... это к чему сказано
0
Maxim Prishchepa
23.12.2016, 20:25
  #13

Не по теме:

too many bukv

0
Liss29
23.12.2016, 20:36     О чем задача?
  #14

Не по теме:

а что поделать)

0
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
23.12.2016, 20:36

Задача на рекурсию (в чем ошибка?)
Привет) Помогите пожалуйста найти ошибку. Задача на рекурсию про 8 ферзей. (В данном фрагменте...

В чем заключается задача анализа схемы?
В чем заключается задача анализа схемы? Нужно по схеме найти формулу(функцию проводимости),...

Найти сумму чётных элементов матрицы, исключая максимальный и минимальный, заменить ей угловые элементы
Ввести целочисленный двумерный массив AN×M, вывести его. Найти сумму его чётных элементов, исключая...

Есть задача, подскажите на чем проще писать?
Собственно задача 1 при наличии определённой ветки в реестре экспортировать её во временный файл и...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
14
Ответ Создать тему
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru