找到最大长度&amp;盒子的宽度</ p>
盒子有四个边,每米的成本是 2宽+ 1长是2500 1长度是1200 长度和宽度的精度应低至0.1米
最大宽度&amp;和长度都是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);
}
答案 0 :(得分:0)
你的问题有点含糊不清,但根据你所说的,我相信这就是你的方法应该是这样的:
#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;
}