gpt4 book ai didi

c - 为什么在 C89 中得到不同的整数除法值?

转载 作者:太空狗 更新时间:2023-10-29 15:13:50 25 4
gpt4 key购买 nike

例如,假设您有这些变量:

int i = 9;
int j = 7;

根据实现,(-i)/j 的值可以是–1–2。怎么可能得到这两种不同的结果呢?

最佳答案

令人惊讶的是,结果是在 C89 中定义的实现:

ANSI draft § 3.3.5

When integers are divided and the division is inexact, if both operands are positive the result of the / operator is the largest integer less than the algebraic quotient and the result of the % operator is positive. If either operand is negative, whether the result of the / operator is the largest integer less than the algebraic quotient or the smallest integer greater than the algebraic quotient is implementation-defined

然而这在 C99 中有所改变

N1256 § 6.5.5/6

When integers are divided, the result of the / operator is the algebraic quotient with any fractional part discarded*

带脚注:

* This is often called "truncation toward zero"

澄清一下,“实现定义”意味着实现必须决定是哪一个,这并不意味着有时你会得到一件事,有时你会得到另一件事(除非实现定义它做一些非常奇怪的事情) ,我猜)。

关于c - 为什么在 C89 中得到不同的整数除法值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29991832/

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