find the maximum box width & length with the constraints
find the maximum of length & width of a box
there are four sides of a box, the cost per meter is 2 width + 1 length is 2500 1 length is 1200 The accuracy of length and width should be down to 0.1 meter
the max width & and length both are 100 meters, the followings is my code, it should be wrong, the tutor ask me to use two for loops to find out the answer, but i don't have ideas... anyone can help?
#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_ar开发者_Go百科ea = 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);
}
Your question is a little ambiguous, but based on what you've said I believe this is what your approach should look like:
#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;
}
精彩评论