编写程序,计算非负数$x$的算术平方根, 要求采用三种实现: 1) for语句; 2) while语句; 3) do-while语句.
时间: 2024-05-10 20:21:37 浏览: 67
1) for语句实现算术平方根:
```c++
#include <iostream>
#include <cmath>
using namespace std;
int main() {
double x;
cout << "请输入非负数x:";
cin >> x;
double sqrt_x = -1; // 初始化sqrt_x为-1
for (double i = 0; i <= x; i += 0.001) {
if (abs(i * i - x) < 0.001) { // 判断i是否为平方根
sqrt_x = i;
break;
}
}
if (sqrt_x == -1)
cout << "计算失败!" << endl;
else
cout << "算术平方根为:" << sqrt_x << endl;
return 0;
}
```
2) while语句实现算术平方根:
```c++
#include <iostream>
#include <cmath>
using namespace std;
int main() {
double x;
cout << "请输入非负数x:";
cin >> x;
double sqrt_x = -1; // 初始化sqrt_x为-1
double i = 0;
while (i <= x) {
if (abs(i * i - x) < 0.001) { // 判断i是否为平方根
sqrt_x = i;
break;
}
i += 0.001;
}
if (sqrt_x == -1)
cout << "计算失败!" << endl;
else
cout << "算术平方根为:" << sqrt_x << endl;
return 0;
}
```
3) do-while语句实现算术平方根:
```c++
#include <iostream>
#include <cmath>
using namespace std;
int main() {
double x;
cout << "请输入非负数x:";
cin >> x;
double sqrt_x = -1; // 初始化sqrt_x为-1
double i = 0;
do {
if (abs(i * i - x) < 0.001) { // 判断i是否为平方根
sqrt_x = i;
break;
}
i += 0.001;
} while (i <= x);
if (sqrt_x == -1)
cout << "计算失败!" << endl;
else
cout << "算术平方根为:" << sqrt_x << endl;
return 0;
}
```
阅读全文