Reputation: 141
Here is my program:
I'm new to coding, as much as I can tell, there is no problem with this code.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int X;
int Y;
int S = X + Y;
int D = X - Y;
double M = X / Y;
printf("Entrer X:");
scanf("%d", X);
printf("Entrer Y:");
scanf("%d", Y);
printf("%f", M);
}
Upvotes: 0
Views: 66
Reputation: 27119
You seem a bit confused about what assignment means.
When you do this
int S = X + Y;
you're actually making that calculation, you're not saying "when the program encounters S
later it should carry out the calculation".
You need to use values when you actually have them.
Also, scanf
expects the address of a variable, not the variable itself (so &X
, not X
).
So:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int X;
int Y;
printf("Entrer X:");
scanf("%d", &X);
printf("Entrer Y:");
scanf("%d", &Y);
double M = X / Y;
printf("%f", M);
}
Upvotes: 1
Reputation:
If you enable warnings and treat warnings as errors, you will get output like this:
$ gcc -Wall -Werror -o scratch main.c
main.c:12:17: error: format specifies type 'int *' but the argument has type 'int' [-Werror,-Wformat]
scanf("%d", X);
~~ ^
main.c:14:17: error: format specifies type 'int *' but the argument has type 'int' [-Werror,-Wformat]
scanf("%d", Y);
~~ ^
main.c:7:9: error: unused variable 'S' [-Werror,-Wunused-variable]
int S = X + Y;
^
main.c:8:9: error: unused variable 'D' [-Werror,-Wunused-variable]
int D = X - Y;
^
main.c:7:13: error: variable 'X' is uninitialized when used here [-Werror,-Wuninitialized]
int S = X + Y;
^
main.c:5:10: note: initialize the variable 'X' to silence this warning
int X;
^
= 0
main.c:7:17: error: variable 'Y' is uninitialized when used here [-Werror,-Wuninitialized]
int S = X + Y;
^
main.c:6:10: note: initialize the variable 'Y' to silence this warning
int Y;
^
= 0
6 errors generated.
This should get you started down the path to fixing your problem.
Upvotes: 0
Reputation: 311393
X
and Y
aren't initialized when you attempt to use them. Specifically, while you should never depend on this undefined behavior, many compilers will initialize an int
with a 0
, so when you calculate M
, your program probably crashes because of the zero-division.
Upvotes: 0
Reputation: 310990
Variables X and Y are not initialized and have indeterminate values.
Arguments of these calls must be pointers
scanf("%d", X);
scanf("%d", Y);
that is
scanf("%d", &X);
scanf("%d", &Y);
And it seems you at first need to enter values for the variables X and Y and only after that use them in expressions.
Also in this statement
double M = X / Y;
in the right hand side of the assignment there is used the integer arithmetic. You should write
double M = ( double )X / Y;
Upvotes: 0