This is my code.
#include <stdio.h>
/*
Write a C program that accepts two integers from the user then outputs the sum, difference, product, and division of the two integers.
*/
float main()
{
float x, y; //defining input variables and the output/answer
printf("Input the first number: %f", x); //user inputs 1st number
scanf("%f", &x);
printf("Input the second number: %f", y); //user inputs 2nd number
scanf("%f", &y);
printf("n");
//math
float sum = x + y;
float diff = x - y;
float product = x * y;
float div = x / y;
//outputting the math
printf("The sum is: %.2fn", sum);
printf("The difference is: %.2fn", diff);
printf("The product is: %.2fn", product);
printf("The division is: %.2fn", div);
return 0.0;
}
Yes, I do want it to be float variables and not int so that it can calculate division more accurately. Doing so will avoid it outputting 2/3 = 0.
4
main()
usually returns anint
.float x, y
are not initialized and printing an indeterminate value is not a useful thing to do.- Always check the return value of
scanf()
otherwise your variable(s) may be indeterminate. - (Not fixed) Prefer
double
overfloat
. - (Not fixed) C 2023 6.5.5 §6 says “if the value of the second operand is zero, the behavior is undefined.” but it is a valid IEEE 754 number namely -Inf or +Inf. Add guard if before the division if that doesn’t work for you.
#include <stdio.h>
int main() {
float x;
printf("Input the first number: ");
if(scanf("%f", &x) != 1) {
printf("scanf failedn");
return 1;
}
float y;
printf("Input the second number: ");
if(scanf("%f", &y) != 1) {
printf("scanf failedn");
return 1;
}
printf("n");
float sum = x + y;
printf("The sum is: %.2fn", sum);
float diff = x - y;
printf("The difference is: %.2fn", diff);
float product = x * y;
printf("The product is: %.2fn", product);
float div = x / y;
printf("The division is: %.2fn", div);
}
and example run:
Input the first number: 2
Input the second number: 3
The sum is: 5.00
The difference is: -1.00
The product is: 6.00
The division is: 0.67
18