JavaScript 程序:检查数字的最后一位是否相同

要理解此示例,您应了解以下 JavaScript 编程 主题


示例:检查最后一位数字

/* program to check whether the last digit of three
numbers is same */

// take input
const a = prompt('Enter a first integer: ');
const b = prompt('Enter a second integer: ');
const c = prompt('Enter a third integer: ');

// find the last digit
const result1 = a % 10;
const result2 = b % 10;
const result3 = c % 10;

// compare the last digits
if(result1 == result2 && result1 == result3) {
    console.log(`${a}, ${b} and ${c} have the same last digit.`);
}
else {
    console.log(`${a}, ${b} and ${c} have different last digit.`);
}

输出

Enter a first integer: 8
Enter a second integer: 38
Enter a third integer: 88
8, 38 and 88 have the same last digit.

在上面的示例中,要求用户输入三个整数。

三个整数值存储在 变量 abc 中。

整数值的最后一位数字使用模运算符 % 来计算。

% 返回余数。例如,58 % 10 返回 8

所有最后一位数字然后使用 if..else 语句和逻辑与运算符 && 进行比较。


另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战