错误的浮点除法导致c

时间:2017-03-31 16:06:00

标签: c

void four_corners(float A[rows][columns]){
int up,down,right,left;
int x=2;
A[0][0]=(float)(up+left)/(float)(x);
A[0][19]=(float)(up+right)/(float)(x);
A[9][0]=(float)(down+left)/(float)(x);
A[9][19]=(float)(down+right)/(float)(x);}

当我在数组中插入四个值时,我没有得到正确的值。我的代码出了什么问题?

1 个答案:

答案 0 :(得分:1)

试试这个:

#include <stdio.h>
#include <conio.h>
#include <string.h>

#define W 10
#define H 20

void four_corners(float A[W][H], int up, int down, int right, int left) {
    int x = 2;
    A[0][0] = (float)(up + left) / (float)(x);
    A[0][19] = (float)(up + right) / (float)(x);
    A[9][0] = (float)(down + left) / (float)(x);
    A[9][19] = (float)(down + right) / (float)(x);
}

void print_board(float A[W][H]) {
    for (int i = 0; i < W; i++) {
        for (int j = 0; j < H; j++) {
            printf("%.1f ", A[i][j]);
        }
    }
}
int main(int argc, char *argv[]) {
    float A[W][H];
    memset(A, 0, W * H * sizeof(float));
    four_corners(A, 1, 2, 3, 4);
    print_board(A);
    getch();
}

基本上,您在代码中遇到的问题是updownrightleft都是局部变量,它们只对four_corners函数。你认为在另一个范围内执行scanf时它们已被正确初始化,但它们实际上并非如此。如果您希望它们对scanf的范围和four_corners范围可见,您可以将它们作为参数传递给函数,或者将它们设置为全局。我建议你阅读更多关于C scopes的内容,这对你来说将是明确的。快乐的编码!

相关问题