判斷敘述式
1.notebook
2.影片栽要
3.測驗
4.學習卡
5.115103138%5+1
Square Numbers Ending in 5
📌 Problem Description
Write a program to calculate the square of a number only if its least significant digit (the last digit) is 5.
If the number ends in 5, the program calculates and displays its square. Otherwise, the program informs the user that the number does not end in 5.
💡 Example
Example 1:
Enter the number: 25
Square = 625
Example 2:
Enter the number: 13
The number does not end in 5.
🧠 Algorithm
- Ask the user to enter an integer.
- Use the modulo operator (
%) to check the last digit of the number. - If
number % 10 == 5, calculate the square of the number. - Display the result.
- Otherwise, display a message indicating that the number does not end in
5.
💻 Source Code (C)
#include <stdio.h>
int main() {
int number;
printf("Enter the number: ");
scanf("%d", &number);
if (number % 10 == 5) {
printf("Square = %d\n", number * number);
} else {
printf("The number does not end in 5.\n");
}
return 0;
}
📖 Explanation
scanf("%d", &number);reads an integer entered by the user.number % 10returns the remainder after dividing the number by 10, which identifies its last digit.number % 10 == 5checks whether the last digit is5.number * numbercalculates the square of the number.if-elsedetermines whether the square should be calculated and displayed.
🚀 How to Run
- Save the program as
main.c. - Compile the program using GCC:
gcc main.c -o main - Run the program:
./mainOn Windows, run:
main.exe
🎯 Learning Objectives
- Understand conditional statements (
if-else). - Learn how to use the modulo operator (
%). - Practice user input and output in C.
- Apply arithmetic operations to calculate squares.
📝 Notes
This program checks the last digit of an integer before calculating its square. The example uses the C language and is intended for beginners learning conditional statements and arithmetic operators.
Language: C
Topic: Conditional Statements, Modulo Operator, Arithmetic Operations










留言
張貼留言