用c++分治法编写完整代码,实现 pow(x,n),即计算 x 的整数 n 次幂函数,要求在输入一个实数 x 和一个整数 n 后,能够计算出值,当x=0时候输入结束,并运用前端技术(不要使用后端技术),将此程序在网页上进行显示,并写出前端代码,将具体运算用js写出,最后运用css将程序页面进行美化。
时间: 2023-07-14 18:12:46 浏览: 98
以下是使用分治法实现 pow(x,n) 的 C++ 代码:
```c++
#include <iostream>
using namespace std;
double power(double x, int n) {
if (n == 0) return 1.0;
double half = power(x, n / 2);
if (n % 2 == 0) return half * half;
else if (n > 0) return half * half * x;
else return half * half / x;
}
int main() {
double x;
int n;
while (true) {
cout << "Please enter x and n: ";
cin >> x >> n;
if (x == 0) break;
cout << "pow(" << x << "," << n << ") = " << power(x, n) << endl;
}
return 0;
}
```
以下是前端页面的 HTML 和 JavaScript 代码:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>pow(x,n) Calculator</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
}
input[type="text"], input[type="number"] {
width: 150px;
padding: 10px;
margin: 10px;
border-radius: 5px;
border: 1px solid #ccc;
font-size: 16px;
box-sizing: border-box;
}
input[type="button"] {
width: 100px;
padding: 10px;
margin: 10px;
border-radius: 5px;
border: none;
background-color: #007bff;
color: #fff;
font-size: 16px;
cursor: pointer;
}
#result {
font-size: 24px;
font-weight: bold;
margin: 20px;
}
</style>
</head>
<body>
<h1>pow(x,n) Calculator</h1>
<form>
<label for="x">x:</label>
<input type="text" id="x" name="x" placeholder="Enter x"><br>
<label for="n">n:</label>
<input type="number" id="n" name="n" placeholder="Enter n"><br>
<input type="button" value="Calculate" onclick="calculate()">
</form>
<div id="result"></div>
<script>
function calculate() {
var x = parseFloat(document.getElementById("x").value);
var n = parseInt(document.getElementById("n").value);
if (isNaN(x) || isNaN(n)) {
alert("Please enter valid input");
return;
}
var result = power(x, n);
document.getElementById("result").innerHTML = "pow(" + x + "," + n + ") = " + result;
}
function power(x, n) {
if (n == 0) return 1.0;
var half = power(x, Math.floor(n / 2));
if (n % 2 == 0) return half * half;
else if (n > 0) return half * half * x;
else return half * half / x;
}
</script>
</body>
</html>
```
使用 CSS 对页面进行美化是一个比较主观的过程,下面是一个简单的样式表,仅供参考:
```css
body {
background-color: #fafafa;
}
h1 {
margin-top: 50px;
margin-bottom: 30px;
color: #007bff;
}
form {
display: inline-block;
text-align: left;
border-radius: 5px;
border: 1px solid #ccc;
box-shadow: 0 2px 2px rgba(0, 0, 0, 0.1);
}
label {
display: block;
margin: 10px;
font-size: 16px;
font-weight: bold;
}
input[type="text"], input[type="number"] {
display: block;
margin: 10px;
font-size: 16px;
font-family: Arial, sans-serif;
}
input[type="button"] {
display: block;
margin: 20px auto;
font-size: 16px;
font-weight: bold;
background-color: #007bff;
color: #fff;
border: none;
border-radius: 5px;
padding: 10px 20px;
cursor: pointer;
}
#result {
margin-top: 50px;
font-size: 24px;
font-weight: bold;
color: #007bff;
}
```
阅读全文