Menu
CoddyTech

除法与类型转换

Coddy 面向 C# 开发者的 PHP 课程的第 4 课,共 48 课。

C# 整数除法会向零截断,对于这些值,其行为与 PHP 的 intdiv 一致。PHP 的 / 可能会得到浮点数,而不是整数商。C# 的 int 是 32 位的,checked/unchecked 上下文会影响溢出的处理方式;PHP 整数及其溢出行为遵循不同的约定。

PHP 的 / 用于计算除法,结果可能是浮点数。intdiv 会将商向零截断;% 表示整数余数。将浮点数强制转换为 int 也会向零截断,但在转换前验证输入,可以避免意外接受不需要的文本。金额示例请使用以分为单位的整数。

C# 程序

#nullable enable
using System;
using System.Collections.Generic;
using System.Linq;

class Program {

 static void Main() {
  Console.WriteLine((-7/3)+":"+(-7%3));
 }
}

源代码输出:

-2:-1

PHP 程序

demo.php

<?php
declare(strict_types=1);
echo intdiv(-7,3),":",(-7%3),"\n";

PHP 输出:

-2:-1
challenge icon

挑战

简单

输入是 0 到 1000000 之间的秒数。splitTime 返回一个包含两个整数的列表:[整分钟数,剩余秒数]。驱动程序会输出分钟:秒。

提供的主脚本会从标准输入读取一个 JSON 值,检查指定的公共 API,并输出结果。实现模块声明时不要打印内容;不要替换启动器,也不要从模块读取输入。输入符合指定的类型和范围。

编辑 Functions.php。main.php 是锁定的入口文件。依赖项使用 require_once __DIR__ 和相对文件名。

亲手试试

<?php
declare(strict_types=1);
require_once __DIR__."/Functions.php";
function ensure(bool $ok,string $message):void{if(!$ok)throw new RuntimeException("API: ".$message);}

$input=json_decode(trim(stream_get_contents(STDIN)),true,512,JSON_THROW_ON_ERROR);
ensure(splitTime(61)===[1,1] && splitTime(120)===[2,0],"splitTime");
echo implode(":",splitTime($input)),"\n";
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

面向 C# 开发者的 PHP中的所有课

自己练习: PHP 在线编译器