gpt4 book ai didi

c - 为什么模数 (%) 运算符适用于 char 但不适用于浮点类型?

转载 作者:太空宇宙 更新时间:2023-11-04 00:37:33 26 4
gpt4 key购买 nike

#include <stdio.h>

int main()
{
char c;
c=10;
if(c%2==0)
printf("Yes");
return 0;
}

上面的代码打印"is"。有人能说出为什么模数运算符适用于 charint 但不适用于 double 等吗?

最佳答案

您已经收到解释为什么 % 是为 char 定义的评论:它是为所有整数类型定义的,在 C 中,char 是一个整数类型。其他一些语言确实定义了不支持算术运算的独特 char 类型,但 C 不是其中之一。

但要回答为什么它没有为浮点类型定义:历史。没有技术原因无法为浮点类型定义 % 运算符。以下是 C99 的基本原理:

6.5.5 Multiplicative operators

[...]

The C89 Committee rejected extending the % operator to work on floating types as such usage would duplicate the facility provided by fmod (see §7.12.10.1).

正如马夫索后来发现的那样:

7.12.10.1 The fmod functions

[...]

The C89 Committee considered a proposal to use the remainder operator % for this function; but it was rejected because the operators in general correspond to hardware facilities, and fmod is not supported in hardware on most machines.

他们似乎有些矛盾。 % 运算符未扩展,因为 fmod 已经满足了该需求,但是选择了 fmod 来满足该需求,因为委员会不想扩展% 运算符?它们不可能同时为真。

我怀疑其中一个原因是最初的原因,另一个是后来没有重新考虑该决定的原因,但不知道哪个是第一个。无论哪种方式,都简单地决定 % 不会执行此操作。

关于c - 为什么模数 (%) 运算符适用于 char 但不适用于浮点类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25340496/

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