C语言中float%float报错‘表达式必须具有整数类型’原因咨询
Let me break this down clearly for you:
The root cause is that in languages like C/C++, the
%(modulo) operator is explicitly designed to work only with integer types (likeint,long,char, etc.) as per the language standard. It’s tied directly to integer division logic, where the result represents the remainder after dividing two whole numbers.Floating-point values (like
20.4or4.4) don’t fit the%operator’s intended use case. If you need to calculate the remainder of a division involving floats or doubles, you should use the standard library functionfmod()instead. For example, instead of writing20.4 % 4.4, you’d callfmod(20.4, 4.4)to get the correct floating-point remainder.Quick side note: This behavior isn’t universal across all languages. For example, Python allows using
%with floating-point numbers because its implementation of the operator is broader. But in C/C++ (which I assume you’re working with given the error message), the strict integer type requirement for%is non-negotiable.
So the error is just the compiler enforcing the language’s core rules—% only works with integers, use fmod() for floating-point remainder calculations!
内容的提问来源于stack exchange,提问作者Dean Movy

