所以我是 C 语言的初学者,我正在构建一个可以找到多项式根的程序。我的任务是打印出分数和整数的根。但我真的不知道该怎么做。我尝试了 float 但基本上它是小数,而 int 不打印除整数之外的任何内容。我希望你可以帮助我。
我包含了迄今为止编写的代码。
int last;
int n=0;
int lastfactor_arr[20];
for(last=1; last<=input[token_counter-1]; last++)
{
if(input[token_counter-1]%last == 0)
{
lastfactor_arr[n] = last;
printf("factors are: %d\n", lastfactor_arr[n]);
n++;
lastfactor_arr[n] = last * -1;
printf("last factors are: %d\n", lastfactor_arr[n]);
n++;
}
}
printf("Total number of factors are: %d\n", n);
int roots_arr[20];
int answer;
int root;
int k, j, f=0;
int s_root;
int nume, deno;
for(k=0; k<=m-1; k++) //LOOP FOR FIRST FACTOR
{
for(j=0; j<=n-1; j++) //LOOP FOR LAST FACTOR
{
answer = firstfactor_arr[k]/lastfactor_arr[j];
if(answer==0)
{
nume = firstfactor_arr[k];
deno = lastfactor_arr[j];
s_root = (input[token_counter-1]*(nume/deno*nume/deno)) + (input[token_counter-2]*nume/deno) + input[0];
if(s_root == 0)
{
roots_arr[f] = nume/deno;
f++;
}
}
else
{
root = (input[token_counter-1]*(answer*answer)) + (input[token_counter-2]*answer) + input[0];
if(root == 0)
{
roots_arr[f] = answer;
f++;
}
}
}
}
int p;
printf("The rational roots of the input polynomial are: ");
for(p=0; p<=f; p++)
{
printf("%.d,", roots_arr[p]);
}
最佳答案
您想要 div_t
或ldiv_t
在<stdlib.h>
。请参阅 div()
的文档标准库函数。您可以调用此函数来获取除法的商和余数,例如:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
static const int n = 10, d = 7;
const div_t result = div(n, d);
const double x = n/(double)d;
printf("%f = %d %d/%d\n",
x, result.quot, result.rem, d);
return EXIT_SUCCESS;
}
另一种方法是替换 result.quot
与 n/d
和result.rem
与 n%d
。这可以让您删除声明 result
的行,您不再需要它。
关于c - 在 C 中保存分数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32793311/