search
Homephp教程php手册PHP整数取余返回负数的相关解决办法

PHP整数取余返回负数的相关解决办法

Jun 13, 2016 am 11:09 AM
echophpindivualexampleMethodTake remainderusintegerofRelatedsolvenegative numberreturn

我们先来看个例子.

$res = 16244799483;
echo $res%9999999;
// 输出结果为 -5069794, 正确的结果应该是4801107

其实这也算上PHP一个BUG吧.最主要是PHP是个弱类型语言.他内置了机器来判断用户的类型.

但是机器毕竟是机器.也有判断出错的时候.就像上面.所以这时候我们就需要人工干预下.

所以我就想到要用下面的方法来解决PHP整数取余返回负数的问题.

$res = floatval(16244799483);
var_dump($res % 9999999);

我们看到结果还是错误的-5069794.

但是值得注意的是返回是一个int类型的.

详细思考了一下.PHP整数取余返回负数的问题是这样处理的.

PHP取余默认为整数的.

而且当你定义$res = 16244799483;

其实就已经溢出了.所以要加上强制类型转换.变成float类型.

但是这样还不够.因为%这个取模计算还是针对整数的.

所以我们需要一个函数fmod.是针对float类型的.

所以最终PHP整数取余返回负数的解决办法为:

$res = floatval(16244799483);
var_dump(fmod($res,9999999));

这样我们就解决了PHP整数取余返回负数这个问题.:)
 


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment