簡體   English   中英

導致C中無限循環的邏輯錯誤

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM