492. Construct the Rectangle(C语言)


求长和宽嘛,正好和我现在的课题,给处理器做的二维矩阵一样的

很好理解,找到L和W差值最小,就是先对area开方

然后W不断-1去尝试,求余,什么时候能整除,那就是答案

一开始我是这样写的

/**
 * Return an array of size *returnSize.
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* constructRectangle(int area, int* returnSize) {
    int L=0,W=0;
    int a[2];
    *returnSize=2;
    W=sqrt(area);
    while(area%W!=0){
        W--;
    }
    L=area/W;
    return &a;
}
但是显示这样空指针的错误 问了大锤师兄 原来是这样

后来我又改成这样

/**
 * Return an array of size *returnSize.
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* constructRectangle(int area, int* returnSize) {
    int L=0,W=0;
    int *a;
    a=(int*)malloc(sizeof(int)*2);
    *returnSize=2;
    W=sqrt(area);
    while(area%W!=0){
        W--;
    }
    L=area/W;
    return &a;
}
还是出现同样的错误,师兄说a本来就是指针,返回&a就是指针的地址,就不对了

/**
 * Return an array of size *returnSize.
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* constructRectangle(int area, int* returnSize) {
    int L=0,W=0;
    int *a;
    a=(int*)malloc(sizeof(int)*2);
    *returnSize=2;
    W=sqrt(area);
    while(area%W!=0){
        W--;
    }
    a[0]=area/W;
    a[1]=W;
    return a;
}
终于 对了



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值