遇到一个问题,输入为m,n,对m开n次根号,不允许使用任何库函数,结果保留小数点后12位。
// 开根号.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
#include <stdio.h>
#define eps 10E-13
int main()
{
double m, n, result, mid, temp, right, left;
(void)scanf("%lf %lf", &m, &n);
//当n为1的时候单独判断
if (n == 1) {
printf("%.12lf", m);
return 0;
}
if (m == 1) {
printf("%.12lf", m);
return 0;
}
//当n不为1的时候
left = 0;
right = m;
mid = left + (right - left) / 2;
temp = 1.0;
while (temp-m >= eps||temp-m<=-eps) {
temp = 1.0;
for (int i=0;i<n;i++) {
temp = temp * mid;
}
if (temp > m) {
right = mid;
mid = left + (right - left) / 2;
}
else if (temp < m) {
left = mid;
mid = left + (right - left) / 2;
}
else if (temp == m)
{
printf("%.12lf", mid);
break;
}
}
printf("%.12lf", mid);
return 0;
}
来源:CSDN
作者:howiewang123
链接:https://blog.csdn.net/qq_35499422/article/details/104755801