gpt4 book ai didi

c++ - 声明、定义和调用

转载 作者:行者123 更新时间:2023-11-30 17:44:50 32 4
gpt4 key购买 nike

我需要使用此程序更好地理解函数定义、声明和正确调用。我真的需要了解如何使用它们。您能否向我展示编写此程序的正确方法(所有三个都正确并进行解释)?

#include <stdio.h>
#include <math.h>

quad_equation(float a, float b, float c);

int main()

{

float a, b, c, determinant, r1,r2;

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

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

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

if (determinant>0)

{

r1= (-b+sqrt(determinant))/(2*a);

r2= (-b-sqrt(determinant))/(2*a);

printf("Roots are: %.2f and %.2f",r1 , r2);

}

else if (determinant==0) { r1 = r2 = -b/(2*a);

printf("Roots are: %.2f and %.2f", r1, r2);

}


else (determinant<0);

{

printf("Both roots are complex");

}

return 0;

最佳答案

我刚刚在这里解决了这个确切的问题:(我想这是作业的一部分)

https://stackoverflow.com/a/19826495/1253932

另外查看您的代码..您从未使用过函数四元方程..而且您还没有定义函数的类型(int/void/float/char)等。

为了方便起见:(这是完整的代码)--如果有什么不明白的地方可以问我

#include <stdio.h>
#include <math.h>

// function declarations

void twoRoots (float a,float b,float delta);
void oneRoot (float a,float b,float delta);

int main (void)
{
//Local Declarations
float a;
float b;
float c;
float delta;

// float solution;

printf("Input coefficient a.\n");
scanf("%f", &a);
printf("Input coefficient b.\n");
scanf("%f", &b);
printf("Input coefficient c.\n");
scanf("%f", &c);
printf("%0.2fx^2 + %0.2fx + %0.2f\n", a, b, c);

delta = (float)(b*b) - (float)(4.0 * a * c);

printf("delta = %0.2f\n",delta);

if (delta > 0){
twoRoots(a,b,delta);
}else if (delta == 0) {
oneRoot(a,b,delta);
}else if (delta < 0.0){
printf("There are no real roots\n");
}

return 0;
}

void twoRoots (float a,float b,float delta)
{

float xOne;
float xTwo;

float deltaRoot;

printf("There are two distinct roots.\n");
deltaRoot = sqrt(delta);
xOne = (-b + deltaRoot) / (2*a);
xTwo = (-b - deltaRoot) / (2*a);
printf("%.2f", xOne);
printf("%.2f", xTwo);
}



void oneRoot(float a,float b,float delta)
{

float xOne;
// float xTwo;
// float deltaRoot;

printf("There is exactly one distinct root\n");
xOne = -b / (2*a);
printf("%.2f", xOne);

}

编辑:

我根据上述代码编写的稍微优化且功能更好的代码:

http://pastebin.com/GS65PvH6

编辑2:

根据您的评论,您尝试这样做:

printf("Enter coefficients a, b and c: ");
scanf("%f%f%f",&a,&b,&c);

如果您输入如下内容,则会失败:121

因为 scanf 会将整个 121 读取到 a 中,而对于 bc 则没有任何内容(相反,它会将\n(enter) 放入 b 中,将 undefined 放入 c 中)

因此请按照我在代码中使用它的方式使用 scanf

关于c++ - 声明、定义和调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19827009/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com