【实验要求】
- 程序支持用户通过命令行输入非负实数。
- 程序同时输出非负平方根和运行时间。
- 记录蛮力法和二分法的运行时间随着问题规模变化的增长表格。
- 蛮力法的整数区间和小数区间的搜索都使用蛮力法。
- 二分法的整数区间和小数区间的搜索都使用二分法。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define deta 0.0001//每次调节的步长
/**********
author:YXP
e-mail:yxp189@protonmail.com
**********/
double immediate_sqrt(double num);//遍历搜索求解
double dichotomy_sqrt(double num);//二分法求解
int main(int argc, char *argv[])
{
long start, finish;
double totaltime;
printf ("\nPlease type in the NUM:");
double num,root;
scanf ("%lf",&num);
start = clock();
root = immediate_sqrt(num); //蛮力法
//root = dichotomy_sqrt(num);//二分法
finish = clock();
totaltime = (double)((finish-start)/CLOCKS_PER_SEC);
printf(">>程序运行时间%.8f秒\n",totaltime);
printf (">>The root=%lf",root);
return 0;
}
double immediate_sqrt(double num)
{
double root,temp;
for (temp = 0;((root+deta)*(root+deta))<num;){
root += deta;
}
return root;
}
double dichotomy_sqrt(double num)
{
double root,mid,head=0,tail=num;
while ((tail -head )>deta){
mid = (head+tail)/2;
if (mid*mid == num){
root = mid;
goto AAA;
}
if ((mid*mid)>num){
tail = mid;
}else{
head = mid;
}
}
root = mid;
AAA:;
return root;
}