I've been struggling with the following program that helps me cheat in my maths class calculating the quadratic equation:
/*Improved version of my maths cheat code -w-,
this program has the same functionality as the last but with
cleaner and more correct code. Notes taken from the post made in
codereview.stackechange to make it less of a dumpster fire.
The program is not functional already.*/
#include<stdio.h>
#include<math.h>
double a,b,c,d;
//Get values of the equation
void get_values (void){
printf("Dame el valor de a: ");
scanf("%g", &a);
printf("Dame el valor de b: ");
scanf("%g", &b);
printf("Dame el valor de c: ");
scanf("%g", &c);
}
//Calculates the discriminante
double discriminante (double a, double b, double c){
double result;
result = b*b-4*a*c;
return result;
}
//Prints the result of the equation based on the square root
//of the discriminate
void display (double d){
if (d>0){
printf("El resultado es: (%g±%g)/%g\n", -b, sqrt(d), a*2);
}
else if (d<0){
printf("El resultado es: (%g±%gi)/%g\n", -b, sqrt(-d), a*2);
}
else { // d == 0
printf("El resultado es: %g/%g\n", b, a*2);
}
}
int main(){
get_values();
d = discriminante(a,b,c);
printf("El valor del discriminante es: %g\n",d);
display(d);
return 0;
}
I made a post in codereview.stackexchange to get some feedback on my code. After rewritting the thing in a cleaner generally better way, I found the small issue that the functions never take the input properly. I've checked the scanf and converters for an hour now, and I'm just baffled at this point on why it just refuses to take input properly. Did I use an improper converter or did I made an error at discriminante?
%g in scanf() is for reading float. You should use %lg to read double.
Note that using %g in printf() to print double is fine.
Related
This question already has answers here:
How to compile C code in Linux to run on Windows? [duplicate]
(4 answers)
Closed 2 years ago.
I started learning how to program last month (and have been making really slow progress ever since), so I really don't know much about stuff.
I code in a Linux (Ubuntu 20.04) and I use VSCode, Sublime, and Code::Blocks (trying to find the perfect IDE for me). I want to learn how to create an executable Windows file so I can share the program I made with my friends (they're all Windows users). Even though it's a really silly objective, learning how to do that will certainly be really useful in the future. I'll leave the code below so you can see it if you like.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
// Cute little program that allows the user to choose between calculating factorials, finding the real roots
// of quadratic equations and counting the quantity of even numbers inside the sequence they can tipe.
// I'm a native (Brazilian) Portuguese speaker and therefore the program will communicate with the user through (Brazilian) Portuguese language.
// this function finds real roots of quadratic equations
void findRoots(){
float a, b, c;
printf("Calculadora de raízes de equações do segundo grau. \n Os parâmetros devem ser observados da fórmula: ax² + bx + c\n");
printf("\nInsira o parâmetro 'a':\n");
scanf("%f", &a);
printf("Insira o parâmetro 'b':\n");
scanf("%f", &b);
printf("Insira o parâmetro 'c':\n");
scanf("%f", &c);
float discriminante = pow(b,2) - (4 * a * c);
float sqrtds = sqrt(discriminante);
float x1 = -b - sqrtds;
float x2 = -b + sqrtds;
float den = 2 * a;
if(a == 0){
printf("Essa não é uma equação do segundo grau!\n");
}else {
if (discriminante < 0){
printf("A equação não possui raízes reais\n");
}else if (discriminante == 0) {
float raiz = -b / den;
printf("A única raíz da equação é %f\n", raiz);
} else {
float raiz1 = x1 / den;
float raiz2 = x2 / den;
printf("O discriminante da equação é %f\n", discriminante);
printf("Logo, a equação possui 2 raízes reais. \n Uma delas é %f \n A outra é %f\n", raiz1, raiz2);
}
}
}
//this function calculates factorials
void fatorial(){
int n;
int x = 0;
printf("Calculadora de fatoriais.\n Insira um número até 12: \n");
scanf("%d", &n);
int y = n;
if(n == 0){
printf("0! é 1\n");
}else if ( n < 13 && n > 0){
while ( y > (x + 1) ){
x = x + 1;
n = n * (y - x);
}
printf("%d! é %d\n", y, n);
} else{
printf("O programa não é capaz de calcular esse fatorial.");
}
}
//this function asks the user to enter a sequence and then tells how many even numbers there are in it (it also shows the quantity of odd numbers)
int paridade(){
printf("Digite o tamanho da sequência:\n");
int n;
scanf("%d", &n);
int par = 0;
int impar = 0;
int x = 0;
int y;
while(x < n){
x = x + 1;
printf("Digite o %dº numero inteiro: \n", x);
scanf("%d", &y);
if((y%2) == 0 ){
par = par + 1;
}else {
impar = impar + 1;
}
}
printf("Na sequencia existem %d números pares e %d números ímpares.\n", par, impar);
return 0;
}
// the main functions allows the user to choose between the funcions mentioned above. It also allows the user to finish the program.
int main(){
printf("Bem vindo(a).\n");
int x = 1;
while(x!= 0){
int opcao;
printf("\nEscolha entre:\n -Calcular o fatorial de um número (Insira 1)\n -Calcular raízes de uma equação do segundo grau (Insira 2)\n -Contar a quantidade de números pares ou ímpares em uma sequência (Insira 3)\n -Terminar o programa (Insira 4)\n");
scanf("%d", &opcao);
switch (opcao)
{
case 1:
fatorial(); //calculates factorial
break;
case 2:
findRoots(); //self-explicative
break;
case 3:
paridade();
break;
case 4:
x = 0; /// closes program
break;
default:
printf("Você selecionou uma opção inválida."); // error message (Invalid option)
break;
}
}
printf("Obrigado por usar o programa."); // "thnks for using the program"
return 0;
}
I code in a Linux (Ubuntu 20.04) and I use VSCode, Sublime, and Code::Blocks (trying to find the perfect IDE for me).
The IDE or editor, in general, is orthogonal to the compiler.
I want to learn how to create an executable Windows file so I can share the program I made with my friends (they're all Windows users).
That means you are cross-compiling. That is, targeting a different platform than the one you are running your compiler on. How to do that depends on your compiler, but it is doable in both GCC and Clang.
Having said that, if you have just started, then you may find it a little be complicated. It may require to install extra packages, tweak things or build the compiler. It is usually way easier to setup a VM with Windows and compile (and test!) the program on it.
The same applies in the opposite case: compiling a Linux program under Windows.
Even though it's a really silly objective, learning how to do that will certainly be really useful in the future.
Certainly, but it is not a silly objective at all. Many important projects are cross-compiled every day.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I am trying to write a code that solves quadratic equations. After entering the 3 constants of the equations, nothing happens. The programs ends even though there are conditions.
This is the code. Thank you for the help.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(){
printf("Se va a trabajar con la ecuacion de la forma ax^2+bx+c\n\n" );
float a,b,c,x_1,x_2,x_0;
printf("Ingrese el valor de la constante a: ");
scanf("%f", &a);
printf("Ingrese el valor de la constante b: ");
scanf("%f", &b);
printf("Ingrese el valor de la constante c: ");
scanf("%f", &c);
double dis = b*b-4*a*c;
double sqr = sqrt(dis);
if(sqr<0){
printf("No tiene solucion en los numeros reales");
}
if(sqr==0){
x_0= -b/(2*a);
printf("La solucion es %f", x_0);
}
if(sqr>0){
x_1= (-b + sqr)/(2*a);
x_2= (-b - sqr)/(2*a);
printf("Las soluciones son %f y %f", x_1, x_2);
}
}
If dis < 0, then sqr = sqrt(dis) evaluates to not-a-number (NaN), and NaNs compare always false to anything (even NaN == NaN is false). Therefore, in this case, all your if conditions are false and nothing happens.
Correct your formula, and everything should be fine.
sqrt returns NaN if the argument is negative, and comparing anything to NaN gives false. Hence, if dis is negative, none of your if-statements will be entered. Actually you should check dis instead of it's square root. But there is also a trick to "detect" Nan:
int main(int argc, char** argv) {
double f = sqrt(-1);
if (f != f) {
printf("oh! Not A Number!");
}
}
Here is the code, basically I gotta do the ceasar cipher in C using arrays and chars only, here is what I have so far:
#include <stdio.h>
#include <stdlib.h>
main ()
{
char alfabeto[26] = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
int a=0;
int b=0;
int m=0;
int c=0;
//char letra;
int cont=0;
char k[]={};
printf("Introduzca un primer numero 'a':\n");
scanf(" %i", &a);
printf("Introduzca un segundo numero 'b':\n");
scanf(" %i", &b);
printf("Introduzca una palabra clave entre 4 y 10 letras (cuando termine presione '.'):\n");
//Falta una validacion para la palabra.
for (int j=0;j<10;j++)
{
scanf(" %c",&k[j]);
cont=j; //cuenta la cantidad de elementos
if (k[j]=='.')
{
j=10;
}
}
for(int j=0;j<cont;j++) //Error in this bit I think.
{
for (int i=0;i<26;i++)
{
if (alfabeto[i]==k[j])
{
m=i;
i=26;
}
}
c = ( (a * m) + b );
printf("%c es: %i \t",k[j],c);
}
}
It uses a formula where c=(a*m+b).
m being the position of the original letter for example: A=0 then m=0.
a being a number you choose as well as b.
In my case I chose a=1 and b=3 and the word CESAR as the key word.
According to the formula the output number of each letter should be c.
The output should be:
C es: 5 E es: 7 S es: 21 A es: 3 R es: 20
Yet it is this:
WrongOutput
UPDATE:
I had to correct this:
char k[]={};
Into this:
char k[10]={'\0'};
Now I get the right output:
Right Output
I declare z3 as a complex number and I want the user to enter, but I don't know how to read the real and the imaginary part and save it in z3. I think I can use neither scanf nor get. Here is the code.
void main(void)
{
float complex z1= 1.0 + 3.0 * I;
float complex z2= 1.0 - 4.0 * I;
float complex z3;
float complex sum= z1 + z2;
printf("\nLa suma Z1+Z2 = %.2f %+.2fi\n",crealf(sum),cimagf(sum));
printf("\nIngrese la parte real de Z3... ");
///???????
printf("\nIngrese la parte imaginaria de Z3... ");
///???????
//How can I read and saved a complex number?
}
You can use scanf like this:
typedef struct complex_num
{
float f_real;
float f_img;
}complex_num_t;
complex_num_t get_complex_num()
{
complex_num_t complex_num= {0,0};
printf("Enter real part:");
scanf("%f",&complex_num.f_real);
printf("Enter imaginery part:");
scanf("%f",&complex_num.f_img);
return complex_num;
}
void main(void)
{
float complex z1= 1.0 + 3.0 * I;
float complex z2= 1.0 - 4.0 * I;
float complex z3;
complex_num_t input_num = {0,0};
float complex sum= z1 + z2;
printf("\nLa suma Z1+Z2 = %.2f %+.2fi\n",crealf(sum),cimagf(sum));
/*Metod 1: Ask real and imaginary independently*/
input_num = get_complex_num();
z3 = input_num.f_real + input_num.f_img*I;
printf("\nIngrese la parte real de Z3...%f ",crealf(z3));
printf("\nIngrese la parte imaginaria de Z3...%f ",cimagf(z3));
}
Can someone help me to run this program? I tried this:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(void) {
double Cateto1;
double Cateto2;
double hipotenusa;
printf("dame el primer cateto: ");
scanf("%1f", Cateto1);
fflush(stdout);
printf("dame el segundo cateto: ");
scanf("%1f", &Cateto2);
fflush(stdout);
hipotenusa = sqrt ((Cateto1*Cateto1)+(Cateto2*Cateto2));
printf("hipotenusa= %2f",hipotenusa);
system("pause");
}
I can build it but I can't run it... it gives me:
RUN FAILED (exit value -1.073.741.790, total time: 17s)
scanf("%lf", Cateto1);
↑ ↑
| You are missing a '&' character here
The width specifier for doubles is l, not 1
The first argument to scanf must be "%lf" (as the letter L) to specify that the corresponding output variable is a pointer to double instead of a float. '1' (One) has no meaning for scanf.
The second argument to scanf here is expected to be a pointer to double, and you're giving it a double instead.
I suppose it is a simple typo since you got it right the second time.
Here is the mistake:
scanf("%1f", Cateto1);
Change it to:
scanf("%1f", &Cateto1);
There are a couple of errors:
The syntax of the scanf expression was wrong: "%1f" should be "%lf"
You need to pass the address of Cateto1 (&Cateto1) to scanf
You don't need the fflush
You don't need the system call
Here's the updated code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(void) {
double Cateto1;
double Cateto2;
double hipotenusa;
printf("dame el primer cateto: ");
scanf("%lf", &Cateto1);
printf("dame el segundo cateto: ");
scanf("%lf", &Cateto2);
hipotenusa = sqrt ((Cateto1*Cateto1)+(Cateto2*Cateto2));
printf("hipotenusa= %2f\n",hipotenusa);
}
There is an Error in your code. Instead of
scanf("%1f", Cateto1);
you should write:
scanf("%1f", &Cateto1);
Simple Mistake
scanf("%1f", &Cateto1); // '&' was missing in all scanf statements
#include <stdio.h>
#include <math.h>
int main(void)
{
double Cateto1;
double Cateto2;
double hipotenusa;
printf("dame el primer cateto: ");
scanf("%lf", &Cateto1);
//fflush(stdout);
printf("dame el segundo cateto: ");
scanf("%lf", &Cateto2);
//fflush(stdout);
hipotenusa = sqrt ((Cateto1*Cateto1)+(Cateto2*Cateto2));
printf("hipotenusa= %2f\n",hipotenusa);
//system("pause");
return 0;
}