c - 如何修复适用于某些值但不适用于其他值的代码
问题描述
当我输入一些值时,我得到了答案,但其他值没有,系统保持阻塞
int pgcdfon(mpz_t a, mpz_t b, mpz_t *x, mpz_t *y) {
if (mpz_cmp_ui(a, 0) == 0) {
mpz_set_ui(*x, 0);
mpz_set_ui(*y, 1);
return b;
}
mpz_t x1, y1, res, h;
mpz_init(x1);
mpz_init(y1);
mpz_init(res);
mpz_t o;
mpz_init(o);
mpz_init(h);
mpz_mod(res, b, a);
int pgcd = pgcdfon(res, a, &x1, &y1);
mpz_div(o, b, a);
mpz_mul(h, o, x1);
mpz_sub(*x, y1, h);
mpz_set(*y, x1);
return pgcd;
}
void main() {
mpz_t x, y, q, w, g;
mpz_init(x);
mpz_init(y);
mpz_init(q);
mpz_init(w);
mpz_init(g);
gmp_printf("donner q \n ");
gmp_scanf("%Zd", &q);
gmp_printf("donner w \n");
gmp_scanf("%Zd", &w);
mpz_set(g, (pgcdfon(q, w, &x, &y)));
gmp_printf("\n\n pgcd de (%Zd, %Zd) = %Zd \n\n", q, w, g);
}
解决方案
该类型mpz_t
是(伪装的)数组类型,因此不能从函数返回。您必须更改函数的原型以返回参数中的值out
,而不是返回它。这意味着,像
mpz_t myfun (...) {
mpz_t ret;
mpz_init(ret);
// fill ret with someting
return ret;
}
不能工作,但必须重写为:
void myfun (..., mpz_t *out) {
mpz_t ret;
mpz_init(ret);
// fill ret with stuff
mpz_init(*out); // if not initialized by caller
mpz_set(*out, ret);
}
应用于您的函数的这种技术会产生
void pgcdfon(mpz_t a, mpz_t b, mpz_t *x, mpz_t *y, mpz_t *ret) {
if (mpz_cmp_ui(a, 0) == 0) {
mpz_set_ui(*x, 0);
mpz_set_ui(*y, 1);
mpz_init(*ret);
mpz_set(*ret, b);
return;
}
mpz_t x1, y1, res, h;
mpz_init(x1);
mpz_init(y1);
mpz_init(res);
mpz_t o;
mpz_init(o);
mpz_init(h);
mpz_mod(res, b, a);
mpz_t pgcd;
pgcdfon(res, a, &x1, &y1, &pgcd);
mpz_div(o, b, a);
mpz_mul(h, o, x1);
mpz_sub(*x, y1, h);
mpz_set(*y, x1);
mpz_init(*ret);
mpz_set(*ret, pgcd);
}
int main() {
mpz_t x, y, q, w, g;
mpz_init(x);
mpz_init(y);
mpz_init(q);
mpz_init(w);
mpz_init(g);
gmp_printf("donner q \n ");
gmp_scanf("%Zd", &q);
gmp_printf("donner w \n");
gmp_scanf("%Zd", &w);
pgcdfon(q, w, &x, &y, &g);
gmp_printf("\n\n pgcd de (%Zd, %Zd) = %Zd \n\n", q, w, g);
}
这应该可以按您的预期工作。
推荐阅读
- c# - 在 xamarin 表单中的 CollectionView 的一行中收集一个 Button 的标识符
- asp.net - 如何屏蔽来自 siteA.com 的 url 以从 siteB.com/page1.aspx?id=1234 检索数据 - ( IIS - URLrewrite - ARR)
- amazon-web-services - AWS ECS 任务无法连接到 RDS 数据库
- javascript - Codewars JavaScript 基础问题帮助(数组)
- glsl - 如何在 ALBEDO 上传递着色器颜色
- winapi - 如何将 NotifyIcon 添加到 ATL 进程外服务器
- javascript - 如何在 React Js 中将空格算作字符?
- android - 如何在背景上方显示列表视图并摆脱从列表视图中弹出的黑屏?
- model - raise ValueError('y has 0 samples: %r' % y) ValueError: y has 0 samples: [] (Xin chào, Vui lòng giúp tôi sửa nó, xin cảmơn)
- twitter - 如何使用 twitteroauth 获取 quote_count?