gpt4 book ai didi

c - 尝试写入文件时的文件分段

转载 作者:行者123 更新时间:2023-12-04 05:53:08 27 4
gpt4 key购买 nike

我正在尝试在 C 语言中使用二分法来查找某些方程的根,但是当我尝试将这个过程的每一步都写在一个文件中时,我遇到了“段错误”的问题。这可能是我犯的一个白痴错误,但是我一直试图解决这个问题很长时间。我正在使用 gcc 进行编译,这就是代码:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define R 1.0
#define h 1.0


double function(double a);
void attractor(double *a1, double *a2, double *epsilon);


void attractor(double *a1, double *a2, double *epsilon)
{
FILE* bisection;
double a2_copia, a3, fa1, fa2;

bisection = fopen("bisection-part1.txt", "w");
fa1 = function(*a1);
fa2 = function(*a2);

if(function(*a1) - function(*a2) > 0.0)
*epsilon = function(*a1) - function(*a2);
else
*epsilon = function(*a2) - function(*a1);


fprintf(bisection, "a1 a2 fa1 fa2 epsilon\n");

a2_copia = 0.0;

if(function(*a1) * function(*a2) < 0.0 && *epsilon >= 0.00001)
{
a3 = *a2 - (*a2 - *a1);
a2_copia = *a2;
*a2 = a3;

if(function(*a1) - function(*a2) > 0.0)
*epsilon = function(*a1) - function(*a2);
else
*epsilon = function(*a2) - function(*a1);

if(function(*a1) * function(*a2) < 0.0 && *epsilon >= 0.00001)
{
fprintf(bisection, "%.4f %.4f %.4f %.4f %.4f\n", *a1, *a2, function(*a1), function(*a1), *epsilon);
attractor(a1, a2, epsilon);
}
else
{
*a2 = a2_copia;
*a1 = a3;
if(function(*a1) - function(*a2) > 0)
*epsilon = function(*a1) - function(*a2);
else
*epsilon = function(*a2) - function(*a1);

if(function(*a1) * function(*a2) < 0.0 && *epsilon >= 0.00001)
{
fprintf(bisection, "%.4f %.4f %.4f %.4f %.4f\n", *a1, *a2, function(*a1), function(*a1), *epsilon);
attractor(a1, a2, epsilon);
}
}
}

fa1 = function(*a1);
fa2 = function(*a2);

if(function(*a1) - function(*a2) > 0.0)
*epsilon = function(*a1) - function(*a2);
else
*epsilon = function(*a2) - function(*a1);

fprintf(bisection, "%.4f %.4f %.4f %.4f %.4f\n", a1, a2, fa1, fa2, epsilon);


}

double function(double a)
{
double fa;
fa = (a * cosh(h / (2 * a))) - R;
return fa;
}

int main()
{

double a1, a2, fa1, fa2, epsilon;


a1 = 0.1;
a2 = 0.5;



fa1 = function(a1);
fa2 = function(a2);
if(fa1 - fa2 > 0.0)
epsilon = fa1 - fa2;
else
epsilon = fa2 - fa1;

if(epsilon >= 0.00001)
{
fa1 = function(a1);
fa2 = function(a2);
attractor(&a1, &a2, &epsilon);
fa1 = function(a1);
fa2 = function(a2);
if(fa1 - fa2 > 0.0)
epsilon = fa1 - fa2;
else
epsilon = fa2 - fa1;

}

if(epsilon < 0.0001)
printf("Vanish at %f", a2);
else
printf("ERROR");



return 0;

}

无论如何,谢谢,如果这个问题不合适,我们很抱歉。

最佳答案

这里

fprintf(bisection, "%.4f %.4f %.4f %.4f %.4f\n", a1, a2, fa1, fa2, epsilon); 

你正在通过 double*参数而不是预期的 double .应该
fprintf(bisection, "%.4f %.4f %.4f %.4f %.4f\n", *a1, *a2, fa1, fa2, *epsilon); 

反而。

关于c - 尝试写入文件时的文件分段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9826388/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com