gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 18:06:45 28 4
gpt4 key购买 nike

求盒子的最大长度和宽度

一个盒子有四个面,每米的成本是2个宽度+1个长度是25001长度为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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com