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 6 years ago.
Improve this question
I've got a pretty basic question, why is my code crashing? I'm learning to use pointers and I really don't know why the code crashes after I enter the values of x1,x2,y1 and y2 (this happens in case 3 of the second switch). I've looked everywhere and I can't find a reason. I need to send the values entered in function menuLR, case 3 to the function DistDosPuntos, an then return the values to menuLR,case 3.
Here's my code.
Some of the code is in spanish, however it's not relevant to know how the code is working. In advance thanks for your help and patience, I know this is quite dumb, but I've tried several methods and haven't been able to either solve or understand the problem
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
void menu1();
void menuLR();
void DistDosPuntos();
void menu1()
{
int a;
float m,x1,x2,y1,y2,k,v,d;
printf("MENU PRINCIPAL\n");
printf("1.- La línea Recta \n");
printf("2.- La circunferencia \n");
printf("3.- Coordenaas Polares \n");
printf("4.- Salir\n");
scanf("%d",&a);
switch(a)
{
case 1:
menuLR(&m,&x1,&x2,&y1,&y2,&k,&v,&d);
break;
case 2 :
// ;
break;
case 3 :
//;
break;
case 4 :
break ;
}
}
void menuLR (float *m,float*x1,float *x2,float *y1,float*y2,float*k,float *v,float *d)
{
int b;
printf("LA LINEA RECTA\n");
printf("1.- Ecuación de la recta dada su puendiente y un punto de la misma \n");
printf("2.- Ecuación de la recta que pasa por dos puntos\n");
printf("3.- Distancia entre dos puntos del plano \n");
printf("4.- Punto medio entre dos puntos del plano\n");
printf("5.- Perímetro y área de un triángulo en un plano\n");
printf("6.- Regresar al menú principal\n");
scanf("%d",&b);
switch (b)
{
case 1 :
printf("Introduzca la pendiente de la recta m y el punto P1(x1,y1)\n");
printf("Introduzca m\n");
scanf("%f",m);
printf("Introduzca x1\n");
scanf("%f",x1);
printf("Introduzca y1\n");
scanf("%f",y1);
printf("La ecuación de la recta es:\n");
printf("y-y1 = m(x-x1)\n");
printf("Sustituyendo valores:\n");
printf("y-%f = %f (x-%f) \n" ,*y1,*m,*x1);
printf("Desarrollando y despejando:\n");
*k = ((*m)*(*x1));
printf("y-%f = %fx-%f)\n",*y1,*m,*k);
*v= -*k+*y1;
printf("y=%fx+(%f)\n",*m,*v);
printf("La ecuación de la recta en la forma general 'y=mx+b' es:\n");
printf("y=%fx+(%f)\n",*m,*v);
break;
case 2 :
break;
case 3 :
printf("Introduzca el punto en el plano P1(X1,Y1)\n");
printf("x1:");
scanf("%f",x1);
printf("y1:");
scanf("%f",y1);
printf("Introduzca el punto en el plano P2(X2,Y2)\n");
printf("X2:\n");
scanf("%f",x2);
printf("Y2:\n");
scanf("%f",y2);
DistDosPuntos(&x1,&x2,&y1,&y2,&d);
printf("La distancia entre los puntos P1 y P2 es:\n %f",*d);
break;
case 4 :
// exit ;
break ;
}
}
void DistDosPuntos(float *x1,float *x2, float *y1, float *y2,float *d)
{
*d = sqrt(pow((*x2-*x1),2) + pow((*y2-*y1),2));
}
int main()
{
int a,b;
float m,x1,y1,k,v,d,y2,x2;
menu1(&b,&x1,&y1,&x2,&y2,&m,&k,&v,&d);
DistDosPuntos(&x1,&x2,&y1,&y2,&d);
return 0;
}
I think you are taking the address of a pointer and passing as a pointer in this section:
printf("Y2:\n");
scanf("%f",y2);
// wrong? x1,x2... are *float; Remove the &s
DistDosPuntos(&x1,&x2,&y1,&y2,&d);
The arguments of the function menuLR are are variables with the names x1, etc. These are of type (float *). They happen to have the same name, (though different types), than the variables in your main function. That's why in one case you need no &, whereas in the main function you do.
Related
I can't seem t find why my program is crashing with segmentation fault.
char *nom;
char **tmp=&nom;
printf("Creando ruta ...\n");
printf("\nIntrodueix el id de la ruta: ");
int ID=demanaInt();
int existe=checkIfRutaExisteix(ID);
if(existe==1){
printf("Ja existeix una ruta amb aquesta ID (id ha de ser unica)");
return;
}
printf("\nIntrodueix el nom de la ruta: ");
demanaString(tmp);
printf("\nIntrodueix el numero de parades: ");
int numParades=demanaInt();
Ruta *r = malloc(sizeof(*r) + sizeof(Parades) + sizeof(*(r->parades.coordenades)) * numParades + sizeof(nom));
strcpy(r->nom, nom);
if(numParades!=-1){
r->parades.numParades=numParades;
}else{
return;
}
int c;
for(int i=0;i<numParades;i++){
r->parades.coordenades[i] = malloc(sizeof(*(r->parades.coordenades[i])*2));
printf("Introdueix la coordenada x de la parada numero %d: ", i);
c=demanaInt();
if(c==-1){
return;
}
r->parades.coordenades[i][0]=c;
printf("Introdueix la coordenada y de la parada numero %d: ", i);
c=demanaInt();
if(c==-1){
return;
}
r->parades.coordenades[i][1]=c;
printf("%d, %d\n", r->parades.coordenades[i][0], r->parades.coordenades[i][1]);
}
printf("Introdueix ID regio: ");
r->IDregio=demanaInt();
r->ID=ID;
guardaRutaCSV(r);
Just before asking for an int evreything is correct, but after that I seem to lose information.
This is my output of GDB:
Creando ruta ...
Introdueix el id de la ruta: 4
Introdueix el nom de la ruta: ref
Introdueix el numero de parades: 3
Introdueix la coordenada x de la parada numero 0: 1
Introdueix la coordenada y de la parada numero 0: 2
1, 2
Introdueix la coordenada x de la parada numero 1: 3
Introdueix la coordenada y de la parada numero 1: 4
3, 4
Introdueix la coordenada x de la parada numero 2: 5
Introdueix la coordenada y de la parada numero 2: 6
5, 6
Breakpoint 1, generarRuta () at ruta.c:90
90 printf("Introdueix ID regio: ");
(gdb) p r->parades.coordenades[0][1]
$1 = 2
(gdb) n
91 r->IDregio=demanaInt();
(gdb) p r->parades.coordenades[0][1]
$2 = 2
(gdb) n
Introdueix ID regio: 99
92 r->ID=ID;
(gdb) p r->parades.coordenades[0][1]
No se puede acceder a la memoria en la dirección 0x555500000067
Why is no longer accesible the information inside the array?
PD: here is the struct:
typedef struct _parades{
int numParades;
int *coordenades[];
} Parades;
typedef struct _ruta{
int ID;
Parades parades;
int IDregio;
char nom[];
} Ruta;
A struct with a flexible array member (array with []) can't be used as a member in another struct. From the C spec (6.7.2.1):
A structure or union shall not contain a member with incomplete or function type (hence,
a structure shall not contain an instance of itself, but may contain a pointer to an instance
of itself), except that the last member of a structure with more than one named member
may have incomplete array type; such a structure (and any union containing, possibly
recursively, a member that is such a structure) shall not be a member of a structure or an
element of an array.
The shall here indicates that the compiler should be giving you a diagnostic message for this code. (Parades being such a structure means it can't be used as a member in Ruta)
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
#include <stdio.h>
#include <math.h>
//// PROTOTIPOS DE FUNCIONES
int numeroPagos(int anios);
// devuelve el numero de pagos mensuales
float interesMensual(float interesAnualTantoPorCiento);
// devuelve el interés mensual, correspondiente a un interés anual dado como tanto por ciento
// interesMensual=(1+interesAnual)^(1/12)-1
float pago(float capital, float interesMensual, int numeroPagos);
// devuelve la cuota mensual de la hipoteca
// pago= capital x ((1+interés mensual)n x interés mensual) / ((1+interés mensual)n-1)
// n = numeroPagos
void leerCondicionesHipoteca(float * capital, float * interesAnualTantoPorCiento, int * anios);
// lee por teclado el capital, el interés anual (en %) y el número de años
//printTablaAmortizacion(float capital,float interesAnualTantoPorCiento,float anios);
// muestra la tabla de amortización de la hipoteca que incluye el pago mensual, los intereses
// el capital amortizado y el capital vivo
// intereses = capital vivo anterior * interés mensual
// amortizado = pago mensual – intereses
// capital vivo actual = capital vivo anterior - amortizado
//// IMPLEMENTACION FUNCION PRINCIPAL
int main()
{
float capital,interesAnualTantoPorCiento;
int anios;
leerCondicionesHipoteca(&capital, &interesAnualTantoPorCiento, &anios);
numeroPagos(anios);
interesMensual(interesAnualTantoPorCiento);
pago(capital, interesMensual, numeroPagos);
}
//// IMPLEMENTACION RESTANTES FUNCIONES
void leerCondicionesHipoteca(float * capital, float * interesAnualTantoPorCiento, int * anios)
{
printf("Introduce el capital: ");
scanf("%f", capital);
printf("Introduce el interes anual : ");
scanf("%f", interesAnualTantoPorCiento);
printf("Introduce el numero de anios: ");
scanf("%d", anios);
}
int numeroPagos(int anios)
{
return anios*12;
}
float interesMensual(float interesAnualTantoPorCiento)
{
float n;
n=(pow(1+interesAnualTantoPorCiento,((1/12)-1)));
return n;
}
float pago(float capital, float interesMensual, int numeroPagos)
{
float n,p,interes,anios;
n=numeroPagos;
interes=interesMensual+1;
p= (capital *interes *n * interesMensual)/(interes*(n-1));
printf("pago mensual: %f", p);
}
printTablaAmortizacion(float capital,float interesAnualTantoPorCiento,float anios)
{
}
I don't know what's the problem, I´m trying to use a function inside another one and it gives me this error:
passing 'float (float)' to parameter of incompatible type 'float'
and I have to keep the functions like that, I can just change the inside part of them. So I have tried to put the function inside the other instead using in the main one function first and the other after
The arguments to pago() should be the values returned from numeroPagos() and interesMensual(). You're passing the functions themselves.
int main()
{
float capital,interesAnualTantoPorCiento;
int anios;
leerCondicionesHipoteca(&capital, &interesAnualTantoPorCiento, &anios);
pago(capital, interesMensual(interesAnualTantoPorCiento), numeroPagos(anios));
}
Notice you're passing a function pointer instead of float value here:
pago(capital, interesMensual, numeroPagos);
Both interesMensual and numeroPagos are function pointers.
I'm building a program for the problem set 1 of CS50x called "cash" that is written in C. I don't know how to make the function cant_de_monedas work on my main function, and when I tried to print the return "dinero" after each loop it keeps counting down even after it reachs 0.
//inclusión de librerías
#include <stdio.h>
#include <cs50.h>
//llamado de la función cant_de_monedas para su funcionamiento en main
float cant_de_monedas(float dinero, int monedas);
int main(void)
{
//input del dinero principal
float dinero = get_float("Insertar dinero: ");
//ajuste de monedas a 0
int monedas= 0;
//llama a la función cant_de_monedas
float cambio = cant_de_monedas(dinero, monedas);
printf("Cantidad de monedas de vuelto: %i\n", monedas);
}
//analiza las monedas necesarias de cambio para una cantidad de dinero variable en centavos de dolar
float cant_de_monedas(float dinero, int monedas)
{
//suma una moneda mientras el dinero sea mayor o igual a 25
do
{
monedas++;
dinero=dinero-25;
printf("%f\n", dinero);
}
while (dinero>=25);
//suma una moneda mientras el dinero se encuentre entre 25 y 10 incluído
do
{
monedas++;
dinero=dinero-10;
printf("%f\n", dinero);
}
while (dinero<25 && dinero>=10);
//suma una moneda mientras el dinero se encuentre entre 10 y 5 incluído
do
{
monedas++;
dinero=dinero-5;
printf("%f\n", dinero);
}
while (dinero<10 && dinero>=5);
//suma una moneda mientras el dinero se encuentre entre 5 y 1
do
{
monedas++;
dinero=dinero-1;
printf("%f\n", dinero);
}
while (dinero<5 && dinero>1);
//suma una moneda mientras el dinero sea 1
do
{
monedas++;
dinero=dinero-1;
printf("%f\n", dinero);
}
while (dinero==1);
return monedas;
}
The output that I get from it is:
$ ./cash
Insertar dinero: 51
26.000000
1.000000
-9.000000
-14.000000
-15.000000
-16.000000
Cantidad de monedas de vuelto: 0
I have three remarks:
You seem to be working with floating point numbers, while there can be quite some rounding issues with those. I'd advise you to work with integer values only.
If you do need to work with floating numbers, I advise you to use double instead of float.
Instead of a do-while, just use a while (imagine the condition is never met, then the loop is not executed at all).
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