c - 找到约束下的最大盒子宽度和长度

标签 c

求盒子的最大长度和宽度

一个盒子有四个面,每米的成本是 2个宽度+1个长度是2500 1长度为1200 长、宽精度可达0.1米

最大宽度和长度都是100米,以下是我的代码,应该是错误的,导师要求我使用两个for循环来找出答案,但我没有想法......有人可以帮忙吗?

#include <stdio.h>

struct dimension {
  float length; 
  float width;
};

    void findBox(float amount, struct dimension* dim) {

      /* Enter your code here */
      float i, j;
      float area = 0;
      float max_area = 1000;
      float cost = 0;

      float length=100;
      float width=100;
      cost = length * 2500 + (width * 2500 * 2) + length * 1200;

      while (cost > amount) {

        length -= 0.1;
        width -= 0.1;
        printf("%f",length);
        printf("%f",width);
        cost = length * 2500 + (width * 2500 * 2) + length * 1200;

        if (cost < amount) {
        printf("%f\n", length);
        printf ("%f\n", width);
        cost = length * 2500 + (width * 2500 * 2) + length * 1200;
        printf ("%f\n", cost);
        break;
        }

      }

    }

    int main() {
      struct dimension dim;
      findBox(20000, &dim);

    }

最佳答案

你的问题有点模棱两可,但根据你所说的,我相信你的方法应该是这样的:

#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>
#include <inttypes.h>

typedef struct {
    uint32_t length, width;
} box_t;

bool box_size_from_cost(uint32_t icost, box_t* obox) {
    if(icost > ((50 * 2500) + (50 * 1200)))
        return false;

    uint32_t width     = 0;
    uint32_t length[2] = { 0 };
    uint32_t cost[2]   = { 0 };

    for(; length[0] <= 1000; length[0]++, cost[0] += 120) {
        for(length[1] = length[0], cost[1] = cost[0]; width <= 1000; width += 2, length[1]++, cost[1] += 250) {
            if(cost[1] == icost) {
                if(obox != NULL) {
                    obox->width  = width;
                    obox->length = length[1];
                }
                return true;
            }
        }
    }

    return false;
}

int main(int argc, char** argv) {
    if(argc < 2) {
        printf("Usage: box <cost>\n");
        return EXIT_FAILURE;
    }

    uint32_t cost;
    if(sscanf(argv[1], "%"SCNu32, &cost) == EOF) {
        printf("Error: Invalid cost parameter.\n");
        return EXIT_FAILURE;
    }

    box_t box;
    if(!box_size_from_cost(cost, &box)) {
        printf("No box size costs %"PRIu32".\n", cost);
        return EXIT_FAILURE;
    }

    printf("A box of size %.1fx%.1f costs %"PRIu32".\n", (box.width * 0.1), (box.length * 0.1), cost);
    return EXIT_SUCCESS;
}

关于c - 找到约束下的最大盒子宽度和长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5334763/

相关文章:

c - 索引值不会改变

c - 枚举类型的位运算

c - 访问指针数组以进行读写操作

c - scanf 没有第二次读取输入

c++ - 解决堆栈溢出错误的问题

c - 在 Direct3D11 中通过 CG 使用多个纹理

c - 段错误,结构数组

c++ - 如何在一行中检查没有定义任何预处理器宏?

尝试使用指针打印值时 c 程序失败

c - 用于图像处理的非常快的 memcpy?