sq (under Linux environment)

Is x * x >= 0 necessarily true? In mathematics, maybe we can be 100% sure that this formula is true, but it may not be true on the computer, and it will be equal to a very small negative number.

#include <stdio.h>
#include <stdlib.h>

int sq(int x) {
    return x*x;
}

int main(int argc, char *argv[]) {
    int i;
    for (i = 1; i < argc; i++) {
    int x = atoi(argv[i]);
    int sx = sq(x);
    printf("sq(%d) = %d\n", x, sx);
    }
    return 0;
}

Let's take a look at the results of several runs with parameters: we
Insert picture description here
can see that the numbers such as -1 and 12 are correct, and the following numbers are all mathematically wrong values. This is because the number we input is defined as an int type (integer type) in the program, and the int type in the computer has a maximum value and a minimum value. The range of the int type is (-65536, 65535), once it exceeds this value Overflow will occur.

Guess you like

Origin blog.csdn.net/xiongdan626/article/details/90551965