Oczywiście w moim kodzie występuje zjawisko redundancji i należałoby poprawić go, aby był zgodny z formułą DRY (Don't Repeat Yourself).
#include <iostream>
int main(){
int first_digit,second_digit;
int choice;
bool check = true;
std::cout<<"1: add"<<std::endl;
std::cout<<"2: sub"<<std::endl;
std::cout<<"3: mul"<<std::endl;
std::cout<<"4: div"<<std::endl;
std::cout<<"5: ret"<<std::endl;
while(check){
std::cin>>choice;
switch(choice){
case 1:
std::cin>>first_digit;
std::cin>>second_digit;
std::cout<<"Result: ";std::cout<<first_digit+second_digit<<std::endl;
break;
case 2:
std::cin>>first_digit;
std::cin>>second_digit;
std::cout<<"Result: ";std::cout<<first_digit-second_digit<<std::endl;
break;
case 3:
std::cin>>first_digit;
std::cin>>second_digit;
std::cout<<"Result: ";std::cout<<first_digit*second_digit<<std::endl;
break;
case 4:
std::cin>>first_digit;
std::cin>>second_digit;
std::cout<<"Result: ";std::cout<<(first_digit)/(second_digit)<<std::endl;
break;
case 5:
std::cout<<std::endl;
check = false;
break;
default:
std::cout<<"Digit must be from range 1-4"<<std::endl;
break;
}
}
return 0;
}
Assembly x86 (8086), Nasm, Windows 32-bit:
global _main
extern _printf
extern _scanf
extern _putchar
SECTION .data
msg0: db "%d",0
msg1: db "1: add",0xa,"2: sub",0xa,"3: mul",0xa,"4: div",0xa,0xa,0
integer1: times 4 db 0
integer2: times 4 db 0
integer3: times 4 db 0
msg2: db "true",0
var dd 0
SECTION .text
_main:
push eax
push msg1
call _printf
add esp,8
Loop1:
push integer1
push msg0
call _scanf
pop eax
pop eax
mov eax,[integer1]
cmp eax,1
je addition
cmp eax,2
je subtraction
cmp eax,3
je multiplication
cmp eax,4
je division
cmp eax,5
je exit_exit
jmp Loop1
ret
addition:
push integer1
push msg0
call _scanf
pop eax
pop eax
push integer2
push msg0
call _scanf
pop eax
pop eax
mov eax,[integer1]
mov ebx,[integer2]
add eax,ebx
push eax
push msg0
call _printf
add esp,8
ret
subtraction:
push integer1
push msg0
call _scanf
pop eax
pop eax
push integer2
push msg0
call _scanf
pop eax
pop eax
mov eax,[integer1]
mov ebx,[integer2]
sub eax,ebx
push eax
push msg0
call _printf
add esp,8
ret
multiplication:
push integer1
push msg0
call _scanf
pop eax
pop eax
push integer2
push msg0
call _scanf
pop eax
pop eax
mov eax,[integer1]
mov ebx,[integer2]
mul ebx
push eax
push msg0
call _printf
add esp,8
ret
division:
push integer1
push msg0
call _scanf
pop eax
pop eax
push integer2
push msg0
call _scanf
pop eax
pop eax
mov eax,[integer1]
mov ebx,[integer2]
div ebx
push eax
push msg0
call _printf
add esp,8
ret
exit_exit:
ret
SECTION .bss
; win 32 bit nasm, asm x86