While loop doesn't break no matter what I do [closed] - c

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I have this code, the problem is no matter what value I give to "m" the while keeps looping and I don't know why
Here is the code
#include <stdio.h>
#include <math.h>
#include <conio.h>
int main(void){
float ur, N, h1, h2, h3, l1, l2, l3, uo, w, V, i, lc1, lc2, A1, A2, A3, A4, R1, R2, R3, R4, Req, fl, P;
int m;
uo = 4*M_PI*(pow(10, -7));
printf("\n-- Inicio del Problema --");
printf("\n-- Para conocer las variables revise la imagen en la parte trasera de la portada del disco --");
while (m != 1){
printf("\n-- Introduzca Permeabilidad magnetica relativa\t");
scanf("%f", &ur);
printf("\n-- Introduzca voltaje en volts\t");
scanf("%f", &V);
printf("\n-- Introduzca corriente en amperes\t");
scanf("%f", &i);
printf("\n-- Introduzca el número de espiras\t");
scanf("%f", &N);
printf("\n-- Introduzca las alturas en metros (h1, h2 y h3 separados por espacio)\t");
scanf("%f %f %f", &h1, &h2, &h3);
printf("\n-- Introduzca los largos en metros (l1, l2, y l3 separados por espacio)\t");
scanf("%f %f %f", &l1, &l2, &l3);
printf("\n-- Introduzca la anchura en metros (w)\t");
scanf("%f", &w);
printf("\nur = %f \t V = %f V \t I = %f A \t N = %f espiras \nh1 = %f m \t h2 = %f m \t h3 = %f m \nl1 = %f m \t l2 = %f m \t l3 = %f m \t w = %f m", ur, V, i, N, h1, h2, h3, l1, l2, l3, w);
printf("\nHa introducido correctamente los datos (si = 1, no = 2)? \t");
scanf("%d", m);
}
lc1 = l2+(l1/2)+(l3/2);
lc2 = h2+(h1/2)+(h3/2);
A1 = h1*w;
A2 = l3*w;
A3 = h3*w;
A4 = l1*w;
R1 = lc1/(ur*uo*A1);
R2 = lc2/(ur*uo*A2);
R3 = lc1/(ur*uo*A3);
R4 = lc2/(ur*uo*A4);
Req = R1+R2+R3+R4;
fl = (N*i)/Req;
P = V*i;
printf("\n-- Las áreas son: \nA1 = %f m^2 \nA2 = %f m^2 \nA3 = %f m^2 \nA4 = %f m^2", A1, A2, A3, A4);
printf("\n-- Las reluctancias son: \nR1 = %f A*V/wb \nR2 = %f A*V/wb \nR3 = %f A*V/wb \nR4 = %f A*V/wb", R1, R2, R3, R4);
printf("\n-- La reluctancia equivalente es: \nReq = %f A*V/wb", Req);
printf("\n-- El flujo magnetomotriz es: \nF = %f wb", fl);
printf("\n-- La potencia del sistema es: \nP = %f watts", P);
getch();
return 0;
}
I've tried changing to "m == 2", doing a do-while. No matter what I do is either breaks with any answer or doesn't brake with any answer.
I've also tried putting an if/break inside the loop, both while and do-while, but still has the same problems
If you point me to the problem I'd really appreciate it

Change:
scanf("%d", m);
to:
scanf("%d", &m);
The way it was, m wasn't changing (and it was writing to some unsafe address in memory).
Your compiler should have warning about this, so make sure you have enabled compiler warnings.
Also, you need to assign an initial value to m, probably zero, to force the loop to be entered the first time.

Two problems there:
You are using m uninitialized.
Last statement scanf("%d", m); should be scanf("%d", &m);. Note the & before m.
Any one of them alone will cause undefined behavior. But, a possible reason for the loop to be infinite is scanf("%d", m); storing the input to the address m not at the address of m. So, m can have indeterminate value which may not be equal to 1 and causing the expression m != 1 to be true always.
Suggested reading: What will happen if '&' is not put in a 'scanf' statement in C?.

Try the following corrections :
1) Initialize m (to something different than 1, if you want the while loop to execute).
2) Change scanf("%d", m); to scanf("%d", &m); in order to read in the same variable you use in the condition.

I think this line has problem
scanf("%d", m);
This will be set the value into address with value m instead of set value to m.
The correct should be
scanf("%d", &m);

Related

Input of double is improper eventhoug converter is

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.

How to create a finished, executable console program from code [duplicate]

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.

Solved: Routine with Do While and For make a unknow error GCC Core dump (Segment fault)

After compiling this program with GCC (Linux or Windows or online test compiler), it fails in different ways each time it runs. I don't understand where I made the mistake.
On Ubuntu Linux, the program crashes without printing an answer.
On Windows 10 (MSYS), it loops indefinitely without printing any message.
On an online compiler I tried, it fails with a segmentation fault (and core dump and exit code 139).
Here is the code:
#include <stdio.h>
int main() {
float riga[1][3];
int ciclo = 2;
int calcolo;
float totale;
int codice = 0;
int quanti = 1;
int prezzo = 2;
printf("\n Inserendo una quantita pari a 0 si conclude con il totale");
do {
codice++;
printf("\n Numero: %d Inserire la quantita:", codice);
scanf("%f", &riga[codice][quanti]);
if ( riga[codice][quanti] < 1 ){
printf("\n Calcolo del totale.");
ciclo = 1;
} else {
printf("\n Numero: %d Inserire il prezzo:", codice);
scanf("%f", &riga[codice][prezzo]);
}
//printf("\n Quantita: %f Prezzo: %f", riga[codice -1][quanti], riga[codice -1 ][prezzo]);
//printf("\n Ciclo = %d", ciclo);
} while( ciclo != 1 );
printf("\n Totale in calcolo");
for ( calcolo = 1; calcolo < (codice + 1); calcolo++){
//printf("\n Prezzo = %f",riga[calcolo][prezzo] );
totale = totale + (riga[calcolo][prezzo] * riga[calcolo][quanti]);
}
printf("\n Totale: %f", totale);
return 0;
}
What is wrong with it?
1.don't use uninitialized variables and you should initialize totale.
2.don't pass boundaries of your array or it will cause undefined behavior.
here in this declaration float riga[1][3]; ,first dimension has only one element.Your increment here codice++; is invalid you don't have riga[1][num] you only have riga[0][num].So remove this line codice++; and also check in your while condition that you won't scan more than 3 elements for second dimension of array.
here
for ( calcolo = 1; calcolo < (codice + 1); calcolo++){
totale = totale + (riga[calcolo][prezzo] * riga[calcolo][quanti]);
}
again you are passing boundaries of array. calcolo could only be zero.
as #John Bollinger said underlying point about arrays: they are indexed from 0, not from 1.

Quadratic equation help in C. [closed]

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!");
}
}

Why is my code crashing? [closed]

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.

Resources