[英]Logical error causing infinite loop in C
我正在一个基本C类的项目中工作,该项目涉及从文件中读取多项式方程式,获取导数,并将导数输出回另一个文件。
我正在对数组进行解析,该数组将文件输入的内容保存在我的第一个函数中(在main之后),理论上应该有一个大的while循环,它应该遍历数组并从根本上弄清楚该数组中的所有内容就多项式而言。 目标是将系数和指数放入两个数组之一,一个用于正指数,一个用于负指数,其中元素编号表示该数组元素内部的指数和系数值。
我们遇到的问题是由于某种原因,指数变量永远不会被赋值。 我们认为这是由于if语句中某处可能存在逻辑错误,但是我们似乎无法确定它是什么。 任何帮助将不胜感激。
#include <stdio.h>
#include <string.h>
void function1 (char *, double *, double *);
void function2 (char *, double *, double *);
int main(void)
{
char input [40];
double neg_part[11], pos_part[11];
double cos[11], sin[11], tan[11];
int i=0;
for (i;i<11;i++)
{
neg_part[i]=0;
pos_part[i]=0;
}
FILE *ifp = fopen("functions.txt","r+"), *ofp = fopen("derive.txt","w");
do
{
if (ifp)
while (!feof(ifp))
{
fgets(input, 40, ifp);
function1(&input, &neg_part, &pos_part);
function2 (&input, &neg_part, &pos_part);
}
}while(!feof(ifp));
}
void function1(char *inputptr, double neg_part[], double pos_part[])
{
int exponent, i=0;
double xcoef;
while (*inputptr!='\n')
{
if (isdigit(*(inputptr)))
{
if (*(inputptr+1)==' '|| *(inputptr+1)=='-' || *(inputptr+1)=='+')
{
xcoef= strtol(inputptr, &inputptr, 10);
exponent=0;
pos_part[exponent]=xcoef;
}
else if (*(inputptr+1)=='x')
{
xcoef= strtol(inputptr, &inputptr, 10);
if (*(inputptr+1)== '^')
{
inputptr+2;
exponent=strtol(inputptr, &inputptr, 10);
}
else if(*(inputptr+1)==' ' || *(inputptr+1)=='-' || *(inputptr+1)=='+')
{
exponent=1;
}
}
}
if (!isdigit(*inputptr))
{
if (*inputptr=='x')
{
xcoef=1;
if (*(inputptr+1)=='^')
{
exponent= strtol(inputptr, &inputptr, 10);
}
else if (*(inputptr+1)=='+' || *(inputptr+1)=='-' || *(inputptr+1)==' ')
exponent= 0;
}
}
if (exponent>=0)
{
pos_part[exponent]=xcoef;
}
else if(exponent<0)
{
exponent=exponent*(-1);
neg_part[exponent]=xcoef;
}
i++;
}
}
while (*inputptr!='\n')
inputptr不会移动。 有inputptr+2;
你的意思是inputptr+=2
使inputptr增加2吗?
您有一条语句: inputptr+2;
,这在逻辑上什么都不做。 也许您的意思是inputptr+=2
,它使inputptr增加2?
祝好运。 我想看一下这段代码,看起来很棒!
我将逐行打印出“ here”或其他一些语句,以查看您的代码实际到达的位置。 如果它从不在任何内部if语句中打印“ here”,则可能是您的while条件未得到满足。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.