簡體   English   中英

C-浮點異常

[英]C - floating point exception

我目前正在嘗試讓我的矩形代碼工作。 可悲的是我遇到了浮點異常,但我不知道為什么。 我最初以為是因為可能的零除,但我排除了這一點。 似乎我每次都強制轉換為int,因此甚至不應該有浮點數。

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

int point_on_line(int x, int y, int x1, int y1, int x2, int y2) {
    int eq1 = (y2 - y1) / (x2 - x1);
    int eq2 = eq1 * (x - x1);
    int eq3 = y - y1 - eq2;
    return eq3;
}

int point_in_rectangle(int x, int y, int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4) {
    int l1 = point_on_line(x, y, x1, y1, x2, y2);
    int l2 = point_on_line(x, y, x2, y2, x3, y3);
    int l3 = point_on_line(x, y, x3, y3, x4, y4);
    int l4 = point_on_line(x, y, x4, y4, x1, y1);
    if ((l1 <= 0) && (l2 <= 0) && (l3 <= 0) && (l4 <= 0)) {
        return 1;
    }
    return 0;
}
int main() {
initscr();
noecho();
nodelay(stdscr, TRUE);

int x_max, y_max;

getmaxyx(stdscr, y_max, x_max);
srand(time(NULL));

start_color();
init_pair(0, COLOR_WHITE, COLOR_BLACK);
init_pair(1, COLOR_RED, COLOR_BLACK);
init_pair(2, COLOR_GREEN, COLOR_BLACK);
init_pair(3, COLOR_BLUE, COLOR_BLACK);
init_pair(4, COLOR_YELLOW, COLOR_BLACK);
init_pair(5, COLOR_MAGENTA, COLOR_BLACK);
init_pair(6, COLOR_CYAN, COLOR_BLACK);

int colors[x_max][y_max];
for (int x = 0; x < x_max; x++) {
    for (int y = 0; y < y_max; y++) {
        int col = 0;
        if (point_in_rectangle(x, y, 5, 5, 10, 5, 10, 10, 5, 10) == 1) {
            col = 1;
        }
        colors[x][y] = col;
    }
}

char input = '0';
while(1) {
    char ch = getch();
    if (ch != ERR) {
        input = ch;
    }

    for (int x = 0; x < x_max; x++){
        for (int y = 0; y < y_max; y++) {
            int col = colors[x][y];
            attron(COLOR_PAIR(col));
            mvaddch(y, x, rand() % 200);
            attroff(COLOR_PAIR(col));
        }
    }
    refresh();
}

endwin();

return EXIT_SUCCESS;
}

編譯並執行程序后,它將顯示以下錯誤消息:

Floating point exception (core dumped)

仔細查看函數point_on_line中x1和x2的值。 x1和x2均為5,x2-x1為0。您基本上除以零,得出浮點異常。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM