Just getting started in C programming and learning about overflow. The following code I created has no issues and complies fine. What I want to know is why? For instance when I replace variables product1 and avg1 with the datatype long long why would it result in an output of nan nan. Why would using type double be better than long long when the size in terms of bytes are similar? Also was it valid for me to cast type double when variables are double already.
#include <stdio.h>
int main(void) {
int userNum1;
int userNum2;
int userNum3;
int userNum4;
/* Type your code here. */
scanf("%d %d %d %d", &userNum1, &userNum2, &userNum3, &userNum4);
int product = userNum1 * userNum2 * userNum3 * userNum4;
double product1 = (double)userNum1 * userNum2 * userNum3 * userNum4;
int avg = (userNum1 + userNum2 + userNum3 + userNum4) / 4;
double avg1 = ((double)userNum1 + userNum2 + userNum3 + userNum4) / 4;
printf("%d %d\n", product, avg);
printf("%0.3lf %0.3lf\n", product1, avg1);
return 0;
}
desired output when input is 8 10 5 4
1600 6 //output of ints
1600.000 6.750 //floating points
%lfwithlong long. If you do, it attempts to treat them as floating point values, which obviously won't work. Your compiler should have warned about incompatible formats (make sure your warning level is high enough).doublewhen variables aredoublealready?" The casted variables are notdoublealready, they areint. Casting todoubleensures that floating point arithmetic is used, otherwise it would be integer arithmetic.