我需要在C中实现Shell排序并使用优化版本(其中间隙首先设置为数组/ 2的大小,然后将此数字重复除以2.2).问题是答案并不总是完全排序,我不确定这是因为我的代码中的某些逻辑错误还是Shell排序的一些缺点.
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#define MAX 7
void shellSort(int *a, int size);
void insert(int *a, int next_pos, int gap);
void shellSort(int *a,int size)
{
int gap = floor(size/2);
int next_pos;
while (gap>0)
{
for(next_pos = gap; next_pos < size; next_pos++)
insert(a, next_pos, gap);
if(gap == 2)
gap = 1;
else
gap = (int)(gap/2.2);
}
}
void insert(int *a, int next_pos, int gap)
{
int value = a[next_pos];
while(next_pos >= gap && a[next_pos] < …Run Code Online (Sandbox Code Playgroud) 我正在编写一个程序,使用C中的Newton-Raphson方法找到给定整数n的平方根的近似值.我使用了以下公式:
这是我的代码:
#include <stdio.h>
double newton_raphson(int n, int iter);
double newton_raphson(int n, int iter)
{
if(iter == 0) // base case
return 1;
else // iterative case
return (1/2*(newton_raphson(n, iter-1) + n/(newton_raphson(n, iter-1))));
}
int main()
{
int n;
int i;
printf("Enter a number you want to know the square root of:\n");
fflush(stdout);
scanf("%d", &n);
printf("Enter number of iterations to be worked out:\n");
fflush(stdout);
scanf("%d", &i);
printf("%.3f", newton_raphson(n,i-1));
return 0;
}
Run Code Online (Sandbox Code Playgroud)
当我输入2和3时,预期的输出是1.417(3次迭代后2的平方根)我得到错误-1.#IO.例如,当我输入5和2时,我得到0.000.我调试了它,但仍然无法弄清楚问题是什么.任何帮助是极大的赞赏.
编辑:详细说明输出