gpt4 book ai didi

c - 我的代码是否正确翻译了必须满足的特定条件?

转载 作者:行者123 更新时间:2023-11-30 17:45:52 25 4
gpt4 key购买 nike

我有一个函数,如果获得了特定的“徽章”或“成就”,则返回 1;如果未获得“徽章”,则返回 0;如果 x 和 y 不在列表中,则返回 -1区间 [1, 20]。

为了让函数返回 1,或者换句话说,为了获得徽章,田地必须支持每年四次完整收成(但不支持五次完整收成)

必须满足的第二个条件是每年累计种植成本在 190 至 250 单位之间。

第三个条件是该领域必须能带来利润。

注意:我已经有了这些预定义函数,可以用来帮助我编写此代码: enter image description here

我已经知道我的代码对于第一个和第二个条件可能存在问题,但我只是不知道如何将这些条件转换为我的代码。

这是我的代码:

#include <stdio.h>

#define YEAR 360
#define FULLHARVESTS 4.0

int badgeInQuattro(int x, int y) {
double harv, annucost, fprofit, harvyear;
int quattrobadge;

if ((x >= 1 && x <= 20) && (y >= 1 && y <= 20)) {
harv = harvestTime(x, y);
annucost = pricePerUnit(x, y);
fprofit = fieldProfit(x, y);
harvyear = (YEAR)/(FULLHARVESTS);

if (harv == harvyear && annucost > 190 && annucost < 250 && fprofit > 0) {
quattrobadge = 1;
}
else {
quattrobadge = 0;
}
}
else {
quattrobadge = -1;
}

return quattrobadge;
}

非常感谢任何帮助!

最佳答案

我实际上发现,通过多个退出点可以使代码更具可读性,特别是那些可以尽早检测到的退出点,尤其是在可以轻松查看函数的情况下,例如较短的版本下面。

人们经常将多个退出点作为一个问题,而不理解为什么。这是因为它会使控制流难以理解,而对于非常短的函数来说,这种情况不会发生。因此我会从以下内容开始:

#include <stdio.h>

#define YEAR 360
#define FULLHARVESTS 4.0

int badgeInQuattro(int x, int y) {
double harv, annucost, fprofit, harvyear;

// Catch invalid ranges first.

if (x < 1 || x > 20 || y < 1 || y > 20) return -1;

harv = harvestTime (x, y);
annucost = pricePerUnit (x, y);
fprofit = fieldProfit (x, y);
harvyear = (YEAR) / (FULLHARVESTS);

//printf ("harv = %f\n", harv);
//printf ("annucost = %f\n", annucost);
//printf ("fprofit = %f\n", fprofit);
//printf ("harvyear = %f\n", harvyear);

// Reversing the checks allows for multiple independent return reasons.

if (harv != harvyear) return 0;
if (annucost <= 190 || annucost >= 250) return 0;
if (fprofit <= 0) return 0;

// All those failures above have been avoided, we MUST be okay here.

return 1;
}

我还会(暂时)取消注释掉那些 printf 语句,因为如果您的数据存在问题,应该很快就会显示出问题所在。

关于c - 我的代码是否正确翻译了必须满足的特定条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19536213/

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