2017-06-01 79 views
2

我在C中有一个问题,我需要在一个函数中插入二次方程的系数并返回解和结果的数目。返回一个值作为输出参数

编写接受一系列3支的实数,这是一元二次方程的 系数的程序,该程序将打印出 方程的一些解决方案和解决方案本身。 准则

  • 功能必须与该 返回解决方案作为返回值的数量的功能之一进行加工,并通过输出参数返回 解决方案本身。
  • 每次收到3个号码必须是 。输入将是从一个文件(将在EOF结束)

在我建的功能,而不从文件中读取其间只看到我的作品,我建立了一个返回号码的功能解决办法但还是纠结于如何返回结果作为输出参数 这里是我的代码现在:


int main() 
{ 

    double a, b, c, root1,root2,rootnum; 

    printf("Enter coefficients a, b and c: "); 

    scanf("%lf %lf %lf",&a, &b, &c); 

    rootnum=(rootnumber(a,b,c); 

    printf("the number of roots for this equation is %d ",rootnum); 
} 


int rootnumber (double a,double b, double c) 
{ 

    formula=b*b - 4*a*c; 

    if (formula<0) 

     return 0; 

    if (formula==0) 

     return 1; 
    else 
     return 2; 
} 
+0

'否则返回2' =>'否则返回2;'和'的printf( “根数为这个equationis”)'= >''printf(“这个方程式的根数是”);'也''rootnum =(rootnumber(a,b,c);'=>'rootnum = rootnumber(a,b,c);' – Badda

回答

0
从调用一个任性的括号和其他一些语法错误

除此之外,你有什么迄今看起来很好。要打印出根数,你需要把format specifier和一个参数在printf声明:

printf("the number of roots for this equation is %d\n", rootNum); 

%d是一个int格式说明。

0

这里是您的工作代码:

#include <stdio.h> 

int rootnumber (double a,double b, double c) 
{ 
    double formula = (b*b) - (4*(a)*(c)); 
    if (formula > 0) { 
     return 2; 
    } 
    else if (formula < 0) { 
     return 0; 
    } 
    else { 
     return 1; 
    } 
} 

int main (void) 
{ 
    double a, b, c; 
    printf("Enter coefficients a, b and c: "); 
    scanf("%lf %lf %lf",&a, &b, &c); 
    printf("The number of roots for this equation is %d ", rootnumber(a,b,c)); 
    return 0; 
} 
1

在C中,提供一个“输出参数”通常等于提供一个参数,是一个指针。该函数将该指针取消引用并写入结果。例如;

int some_func(double x, double *y) 
{ 
    *y = 2*x; 
    return 1; 
} 

调用者通常必须提供将接收结果的地址(例如变量)。例如;

int main() 
{ 
    double result; 
    if (some_func(2.0, &result) == 1) 
     printf("%lf\n", result); 
    else 
     printf("Uh oh!\n"); 
    return 0; 
} 

我故意提供了一个例子来说明“输出参数”是什么,但与您实际需要编写的代码没有关系。对于您的问题,您需要提供两个参数(即总共五个参数,三个您已经提供,另外两个指针用于将值返回给调用者)。由于这是一项家庭作业练习,因此我不会解释函数需要通过输出参数返回的WHAT值。毕竟,这是练习的一部分,目的是通过解决这个问题来学习。

0

它只是需要一些健全检查,其现在的工作:

#include<stdio.h> 
int rootnumber(double a, double b, double c); 
int main() 
{ 

    double a, b, c, root1,root2; 
    int rootnum; 

    printf("Enter coefficients a, b and c: "); 

    scanf("%lf %lf %lf",&a, &b, &c); 

    rootnum=rootnumber(a,b,c); 

    printf("the number of roots for this equation is %d", rootnum); 

    return 0; 
} 


int rootnumber(double a, double b, double c) 
{ 

    int formula= (b*b) - (4*a*c); 

    if (formula<0) 

     return 0; 

    if (formula==0) 

     return 1; 
    else 
     return 2; 
} 
+0

thanks,i修复了失踪的“;”但这不是我的问题 –