Equação do segundo grau
Publicado por Gabriel (última atualização em 03/05/2010)
[ Hits: 10.390 ]
Uma brincadeira que eu fiz para resolver uma equação do segundo grau utilizando comandos.
/* This program solves a quadratic equation */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
typedef struct s_cmd_line {
char cmd[4];
float a;
float b;
float c;
} t_cmd_line;
t_cmd_line cmd_line;
char line[100]; /* command line */
void stread () {
int i = 0;
fgets(line,sizeof(line),stdin);
/* cmd */
for (i = 0; i < 4; ++i) {
cmd_line.cmd[i] = line[i];
line[i] = ' '; /* erase the cmd */
}
/* a, b, c */
sscanf(line, "%f %f %f", &cmd_line.a, &cmd_line.b, &cmd_line.c);
}
int main () {
float a = 0, b = 0, c = 0; /* coeficients */
float delta = 0; /* discriminant */
float r1 = 0, r2 = 0; /* roots */
/* Display */
system("clear");
printf("\n==================\n");
printf("Quadratic Equation");
printf("\n==================\n\n");
printf("Welcome. Type 'help' for help.\n\n");
/* Commands */
/*
- zero : clear all the variables
- read %f %f %f : enter new coeficients
- show : show the equation informed
- root : find the roots, the parameter
shows the result in fractions
- exit : kill the program
*/
while (strcmp(cmd_line.cmd,"exit")) {
printf("> ");
stread(); /* read the command line */
/* zero */
if (!strcmp(cmd_line.cmd,"zero")) {
a = 0;
b = 0;
c = 0;
}
/* read */
if (!strcmp(cmd_line.cmd,"read")) {
a = cmd_line.a;
b = cmd_line.b;
c = cmd_line.c;
}
/* show */
if (!strcmp(cmd_line.cmd,"show"))
printf("(%f) x^2 + (%f) x + (%f) = 0\n", a, b, c);
/* root */
if (!strcmp(cmd_line.cmd,"root")) {
if (a != 0) {
/* discriminant */
delta = b * b - 4 * a * c;
r1 = - b / (2*a);
r2 = r1;
if (delta >= 0) {
/* real roots */
r1 = r1 + (sqrt(delta)/(2*a));
r2 = r2 - (sqrt(delta)/(2*a));
printf(" r1 = %f \n r2 = %f\n", r1, r2);
} else {
/* complex roots */
delta = - delta;
printf(" r1 = %f + i %f \n r2 = %f - i %f\n", r1, (sqrt(delta)/(2*a)), r2, (sqrt(delta)/(2*a)));
}
} else { /* a == 0 */
printf("'a' mustn't be zero \n");
}
}
/* help */
if (!strcmp(cmd_line.cmd,"help")) {
printf("\nCommands\n");
printf(" - zero : clear all the variables\n");
printf(" - read %%f %%f %%f : enter new coeficients \n");
printf(" - show : show the equation informed\n");
printf(" - root : find the roots\n - exit : kill the program\n\n");
}
}
printf("\nbye\n\n");
return 0;
}
Barra de progresso em forma de "roda"
Modo Simples de Baixar e Usar o bash-completion
Monitorando o Preço do Bitcoin ou sua Cripto Favorita em Tempo Real com um Widget Flutuante
Instalando partes faltantes do Plasma 6
Adicionar botão "mostrar área de trabalho" no Zorin OS
Como montar um servidor de backup no linux
Estou tentando ser legalista, mas tá complicado! (9)
espelhar monitores nao funciona (2)
SQLITE não quer funcionar no LINUX LMDE6 64 com Lazaruz 4.2 64bit (n... (1)









