最终:账户转账
Coddy 面向 C 开发者的 GDScript 课程的第 48 课,共 48 课。
挑战
简单实现 FundsAccount(initial:int),其中包含 balance;实现静态方法 FundsTransfer.move(source:FundsAccount,target:FundsAccount,n:int)->bool。如果账户为 null、金额为负数或来源账户余额不足,则拒绝转账且不修改任何数据。否则执行一次转账。余额足够时,自转账应成功且余额不变。solve 接收 [a,b,n],并返回 success:a:b。初始余额均为非负数。
输入是 stdin 上的一个 JSON 数组。锁定的 main 会解析它,调用公开 API,并打印 result=,后接返回文本和一个换行符。任何辅助函数都不应打印内容。在处理输入用例之前,独立的固定探测会验证必需的 API 行为;它们不会强制规定实现风格。
完整的 C 参考实现。将这些文件保存在同一目录中,并使用 C17 编译器编译 main.c。头文件提供辅助 API;main 会读取相同的 JSON 数组,并按照相同的结果协议打印内容。无需外部库。
C 文件 account.h:
#ifndef ACCOUNT_H
#define ACCOUNT_H
#include <stdint.h>
struct Account { int64_t balance; };
static inline struct Account account_make(int64_t initial) {
return (struct Account){initial};
}
#endif
C 文件 transfers.h:
#ifndef TRANSFERS_H
#define TRANSFERS_H
#include <stdbool.h>
#include "account.h"
static inline bool transfer_move(struct Account *source,
struct Account *target, int64_t amount) {
if (!source || !target || amount<0 || amount>source->balance) return false;
if (source==target) return true;
/* Match the reference's unchecked 64-bit arithmetic without C overflow. */
uint64_t sum=(uint64_t)target->balance+(uint64_t)amount;
source->balance-=amount;
target->balance=sum <= INT64_MAX ? (int64_t)sum : -1-(int64_t)(UINT64_MAX-sum);
return true;
}
#endif
C 文件 main.c:
#include <stdio.h>
#include <string.h>
#include <inttypes.h>
#include "transfers.h"
int main(int argc, char **argv) {
if (argc>1 && strcmp(argv[1],"--probe")==0) {
struct Account a=account_make(6);
if (transfer_move(NULL,&a,0) || transfer_move(&a,NULL,0) ||
!transfer_move(&a,&a,4) || a.balance!=6 ||
transfer_move(&a,&a,7) || a.balance!=6) return 1;
puts("contract-ok"); return 0;
}
int64_t a,b,n;
if (scanf(" [ %" SCNd64 " , %" SCNd64 " , %" SCNd64 " ]",&a,&b,&n)!=3) return 1;
struct Account source=account_make(a),target=account_make(b);
bool moved=transfer_move(&source,&target,n);
printf("result=%s:%" PRId64 ":%" PRId64 "\n",
moved?"true":"false",source.balance,target.balance);
return 0;
}
你的代码应写在 funds_account.gd、funds_transfer.gd 和 exercise.gd 中。main.gd 存放了提供的输入/输出代码,不能编辑。每个 class_name 类型都要放在与其同名的文件中。
亲手试试
extends Node
func contract_ok(data: Array) -> bool:
var a: FundsAccount = FundsAccount.new(6)
var b: FundsAccount = FundsAccount.new(2)
if FundsTransfer.move(null,b,0) or FundsTransfer.move(a,null,0) or FundsTransfer.move(a,b,7) or FundsTransfer.move(a,b,-1): return false
if a.balance != 6 or b.balance != 2: return false
if not FundsTransfer.move(a,a,4) or a.balance != 6: return false
if not FundsTransfer.move(a,b,3) or a.balance != 3 or b.balance != 5: return false
return true
func _ready() -> void:
var data: Array = JSON.parse_string(OS.read_string_from_stdin())
if not contract_ok(data):
print("API_CONTRACT_FAILED")
return
print("result=" + Exercise.solve(data))
面向 C 开发者的 GDScript中的所有课
自己练习: GDScript 在线编译器