我最近正在尝试编写一段代码,其中程序将使用乘积规则显示函数的导数。该函数可以是以下之一:x^n
、sin(a*x)
或 cos(a*x)
。例如,它可以是一组三个函数,因此文件可能如下所示:
x^7*sin(3.14*x)
cos(4*x)*sin(5.2*x)
cos(2*x)*cos(8*x)
我写了一些本地函数,比如
void derivcc ()
{
double a, b;
fscanf(f,"cos(%lf*x)*cos(%lf*x)",&a, &b);
if (a<0 && b<0)
printf("%lfsin(%lf*x)*cos(%lf*x)+%lfsin(%lf*x)*cos(%lf*x)\n",
-a,a,b,-b,b,a);
else if (a<0 && b>0)
printf("%lfsin(%lf*x)*cos(%lf*x)-%lfsin(%lf*x)*cos(%lf*x)\n",
-a,a,b,b,b,a);
else if (a>0 && b<0)
printf("-%lfsin(%lf*x)*cos(%lf*x)+%lfsin(%lf*x)*cos(%lf*x)\n",
a,a,b,-b,b,a);
else
printf("-%lfsin(%lf*x)*cos(%lf*x)-%lfsin(%lf*x)*cos(%lf*x)\n",
a,a,b,b,b,a);
}
但是,我遇到的问题是在 main 函数中。我想知道我应该如何解决 while 循环,以便本地函数可以工作。这是主要的:
int main(void)
{
FILE * f;
char lines[50];
f=fopen("function.txt", "r");
if (f == NULL)
{
printf("Error with opening the file!/n");
exit (1);
}
int c;
fgets(lines, sizeof(lines), f);
char sin[]="sin";
char cos[]="cos";
char x[]="x^";
char *checkc, *checks, *checkx;
checkc = strstr(lines,cos);
checks = strstr(lines,sin);
checkx = strstr(lines, x);
double a,b;
while((c = getc(f)) != EOF)
{
if (checks == NULL)
{
if (checkc == NULL)
{
derivxx();
}
else
{
if (checkx==NULL)
derivcc();
else
{
if (lines[0] == cos[0])
derivcx();
else
derivxc();
}
}
}
else
{
if (checkc == NULL && checkx == NULL)
{
derivss();
}
else
{
if (checkc == NULL && checkx != NULL)/
{
if (lines[0]==sin[0])
derivsx();
else
derivxs();
}
else if (lines[0]==sin[0])
derivsc();
else
derivcs();
}
}
}
fclose(f);
}
最佳答案
您已经掌握了大部分代码。您只需要稍微重新安排一下即可使其正常工作。这是您拥有的代码:
int c;
fgets(lines, sizeof(lines), f);
char sin[]="sin";
char cos[]="cos";
char x[]="x^";
char *checkc, *checks, *checkx;
checkc = strstr(lines,cos);
checks = strstr(lines,sin);
checkx = strstr(lines, x);
double a,b;
while((c = getc(f)) != EOF)
{
}
代码读取第一行,然后使用 strstr
函数获取有关该行的一些信息。然后 while
循环开始一次读取一个字符。
需要发生的是 while
循环需要一次读取一行。并且 strstr
调用需要在 while
循环中。所以代码应该是这样的:
char sin[]="sin";
char cos[]="cos";
char x[]="x^";
char *checkc, *checks, *checkx;
double a,b;
while(fgets(lines, sizeof(lines), f) != NULL)
{
checkc = strstr(lines,cos);
checks = strstr(lines,sin);
checkx = strstr(lines, x);
}
关于c - while循环涉及到文件和字符串怎么办?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48369557/