Мне нужно лучше понять определение функции, декларации и соответствующие вызовы с помощью этой программы. Мне действительно нужно понять, как их использовать. Не могли бы вы показать мне правильный способ написать эту программу со всеми тремя правильными и объясненными?
#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;
Я просто решил этот точный вопрос здесь: (Я думаю, что это часть задания)
qaru.site/questions/7572257/...
Также смотря на ваш код.. вы никогда не используете уравнение функции quad. Также вы не определили тип функции (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);
}
РЕДАКТИРОВАТЬ:
Несколько более оптимизированный и улучшенный код работы, который я сделал из вышеупомянутого кода:
Edit2:
Из ваших комментариев вы пытаетесь это сделать:
printf("Enter coefficients a, b and c: ");
scanf("%f%f%f",&a,&b,&c);
Это приведет к сбою, если вы введете что-то вроде этого: 121
Beacuse scanf будет считывать все 121
в a
и он не будет иметь ничего для b
, c
(скорее, он поместит \n (введите) в b и не будет определен в c)
Поэтому используйте scanf так, как я использовал его в своем коде
ОК - это полно проблем! Я пытаюсь указать их и показать, что "лучше" выглядит. Надеюсь, это поможет.
quad_equation(float a, float b, float c);
Вероятно, это был "прототип функции". Прототип сообщает компилятору "Я собираюсь использовать эту функцию позже, и вот как это должно быть вызвано, и тип, который он возвращает". Вы не указали тип возврата; возможно, вы хотите использовать int
чтобы сказать, были ли вы найдены корнями или нет, и распечатать результат в функции. Лучше было бы передать пространство для двух возвращаемых значений в качестве параметра:
int quad_equation(float a, float b, float c, float* x1, float* x2);
Теперь мы можем использовать main
программу для ввода ввода/вывода и позволить этой функции решить проблему:
int main(void) {
{
float a, b, c, r1, r2;
int n;
// here you get the inputs; that seems OK
printf("Enter coefficients a, b and c: ");
scanf("%f %f %f",&a,&b,&c);
// now you have to "call your function"
// note that I make sure to follow the prototype: I assign the return value to an int
// and I pass five parameters: the coefficients a, b, c and the address of two variables
// x1 and x2. These addresses will be where the function puts the roots
n = quad_equation(a, b, c, &r1, &r2);
// when the function returns, I can print the results:
printf("There are %d roots:\n", n);
// based on the value of n, I change what I want to print out:
if (n == 2) printf(" %f and ", r1); // when there are two roots I print "root 1 and"
if (n > 0) printf("%f\n", r2); // when there is at least one root, I print it
// note that if n == 0, I would skip both print statements
// and all you would have gotten was "There are 0 roots" in the output
}
int quad_equation(float a, float b, float c, float* x1, float* x2) {
// function that computes roots of quadratic equation
// and returns result in x1 and x2
// it returns the number of roots as the return value of the function
float determinant;
determinant=b*b-4*a*c;
if (determinant>0)
{
*x1 = (-b+sqrt(determinant))/(2*a);
*x2= (-b-sqrt(determinant))/(2*a);
return 2;
}
if (determinant==0) {
*x1 = *x2 = -b/(2*a);
return 1;
}
return 0;
}
float
, а указатель на число с плавающей точкой - т. Е. Эта переменная содержит адрес места, где хранится число с плавающей точкой . Это позволяет функции изменять содержимое этого местоположения, и поэтому она может передавать более одного значения обратно вызывающей программе. Я намеренно дал им другое имя в функции, потому что это одна из вещей, которые вы можете сделать: имя переменной, которую вы используете для ее определения, не обязательно должно быть именем переменной, с которой вы ее вызываете.