Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> PHP

PHP ตรวจสอบหลักสัญญาณทุกตัวหารเลขนั้นลงตัว

ตัวอย่างโค้ด

<?php
function divisibility_check($my_val, $my_digit) {
    return ($my_digit != 0 && $my_val % $my_digit == 0);
}

function divide_digits($n) {
    $temp = $n;  // Fixed: $my_val → $n
    while ($temp > 0) {
        $my_digit = $temp % 10;  // Fixed: $my_val → $temp
        if (!divisibility_check($n, $my_digit)) {  // Fixed: $my_val → $n
            return false;
        }
        $temp = (int)($temp / 10);  // Fixed: /= 10 → int division
    }
    return true;
}

$val = 255;
if (divide_digits($val)) {
    echo "All the numbers can be divided";
} else {
    echo "All the numbers can't be divided";
}
?>

ผลลัพธ์

All the numbers can be divided

Bug Fixes ในโค้ดต้นฉบับ

  • $temp = $my_val; → $temp = $n; (Parameter คือ $n)
  • $my_digit = $my_val % 10; → $temp % 10; (Extract Digit จาก Temp)
  • divisibility_check($my_val, ...) → divisibility_check($n, ...)
  • $temp /= 10; → $temp = (int)($temp / 10); (Integer Division)

ตรวจสอบ 255

Digits: 2, 5, 5

  • 255 % 2 = 1 ≠ 0 → FALSE

ผลลัพธ์ที่ถูกต้องควรเป็น "All the numbers can't be divided"

Correct Test

<?php
$test_cases = [128, 124, 111, 255, 1024];
foreach ($test_cases as $val) {
    echo "$val: " . (divide_digits($val) ? "YES" : "NO") . "\n";
}
// 128: 1,2,8 → 128%1=0, 128%2=0, 128%8=0 → YES
// 124: 1,2,4 → 124%1=0, 124%2=0, 124%4=0 → YES
// 111: 1,1,1 → 111%1=0 → YES
// 255: 2,5,5 → 255%2=1 → NO
// 1024: 1,0,2,4 → has 0 → NO (division by zero)
?>

ผลลัพธ์ที่ถูกต้อง

128: YES
124: YES
111: YES
255: NO
1024: NO