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

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.

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.

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.

storage of a result in a vector

I have tried to store a result in a vector and then to print all those stored values, I think I'm very far, but that's what I was able to develop until now, I'd like some help on what's wrong and how it could you do it, thank you and good night
#include <stdio.h>
int main(void) {
int i;
int x;
int vetor[]={};
int a, b;
int resultado;
printf("Quantos resultados esse vetor vai receber tem ? ");
scanf("%d", &x);
printf("\n");
for(i=1; i<=x; i++){
printf("Digite valores para serem somados e armazenados no vetor:\n");
scanf("%d%d", &a, &b);
resultado = a+b;
resultado = *vetor;
printf("vetor contém: %d\n", *vetor);
}
printf("\n");
printf("você conseguiu !!!");
return 0;
}
`````````````````````````````````````````````````````````````````´´´´
#include <stddef.h>
#include <stdio.h>
#define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]))
#define ARRAY_SSIZE(arr) ((ptrdiff_t)ARRAY_SIZE(arr))
int main(void)
{
ptrdiff_t x;
int a, b;
int resultado;
printf("Quantos resultados esse vetor vai receber tem ? ");
scanf("%ti", &x);
int vector[x] = {0};
printf("\n");
for (ptrdiff_t i = 0; i < ARRAY_SSIZE(vector); i++) {
printf("Digite valores para serem somados e armazenados no vetor:\n");
scanf("%d%d", &a, &b);
resultado = a + b;
vector[i] = resultado;
printf("vetor contém: %d\n", vetor[i]);
}
printf("\n");
printf("você conseguiu !!!\n");
return 0;
}
You should give the array (not vector) a size (x in this case) to create it.
Assignments (a = b;) work this way: the program calculates whatever is on the right hand side, and copies that value into the variable that is on the left hand side of the =.
When you use (access, write, ...) an array, you have to specify the index (position) of the array you want to use.
It is better to use sizeof to calculate the size of an array for loop limits so that if you change the declaration of the array, the code still works (see ARRAY_SIZE, and ARRAY_SSIZE which is a signed version, so that comparison is done between integers of the same sign, to avoid unexpected bugs).
Always end your last printf with a \n, so that it doesn't get mixed with other text in the terminal.

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