ساخت ماشین حساب با زبان جاوا اسکریپت
برای ساخت یک ماشین حساب با استفاده از زبان جاوا اسکریپت، ابتدا نیاز داریم تا یک ساختار HTML ساده ایجاد کنیم. سپس با استفاده از CSS، استایل مناسبی به آن بدهیم. در نهایت، کدهای جاوا اسکریپت را برای انجام محاسبات پیادهسازی میکنیم.
۱. ساختار HTML
ابتدا یک فایل HTML ایجاد کنید و کدهای زیر را داخل آن قرار دهید:
```html
<!DOCTYPE html>
<html lang="fa">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=
- 0">
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="calculator">
<input type="text" id="result" disabled>
<div class="buttons">
<button onclick="clearResult()">C</button>
<button onclick="appendToResult('1')">1</button>
<button onclick="appendToResult('2')">2</button>
<button onclick="appendToResult('3')">3</button>
<button onclick="appendToResult('+')">+</button>
<button onclick="appendToResult('4')">4</button>
<button onclick="appendToResult('5')">5</button>
<button onclick="appendToResult('6')">6</button>
<button onclick="appendToResult('-')">-</button>
<button onclick="appendToResult('7')">7</button>
<button onclick="appendToResult('8')">8</button>
<button onclick="appendToResult('9')">9</button>
<button onclick="appendToResult('*')">*</button>
<button onclick="appendToResult('0')">0</button>
<button onclick="calculateResult()">=</button>
<button onclick="appendToResult('/')">/</button>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
```
۲. استایل CSS
در ادامه، یک فایل CSS به نام `style.css` ایجاد کنید و کدهای زیر را داخل آن قرار دهید:
```css
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
background-color: #f4f4f4;
}
.calculator {
background-color: #fff;
padding: 20px;
border-radius: 10px;
box-shadow: 0 0 10px rgba(0,0,0,
- 1);
input {
width: 100%;
height: 40px;
text-align: right;
margin-bottom: 10px;
font-size: 18px;
}
.buttons {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 10px;
}
button {
height: 40px;
font-size: 18px;
}
```
۳. کد جاوا اسکریپت
حالا یک فایل جاوا اسکریپت به نام `script.js` ایجاد کنید و کدهای زیر را داخل آن قرار دهید:
```javascript
function appendToResult(value) {
document.getElementById("result").value += value;
}
function clearResult() {
document.getElementById("result").value = '';
}
function calculateResult() {
const resultField = document.getElementById("result");
try {
resultField.value = eval(resultField.value);
} catch (e) {
resultField.value = 'خطا';
}
}
```
نتیجهگیری
با انجام مراحل بالا، شما یک ماشین حساب ساده با استفاده از جاوا اسکریپت ایجاد کردهاید. این ماشین حساب امکان انجام عملیاتهای پایهای همچون جمع، تفریق، ضرب و تقسیم را دارد. با افزودن ویژگیهای بیشتر، میتوانید ماشین حساب خود را پیشرفتهتر کنید.
امیدوارم این توضیحات برای شما مفید باشد! اگر سوالی دارید، خوشحال میشوم کمک کنم.