ในบทความนี้ เราจะเข้าใจวิธีการนับจำนวนหลักเป็นจำนวนเต็ม ตัวเลขในจำนวนเต็มจะถูกนับโดยใช้การวนซ้ำและตัวนับ
ด้านล่างนี้เป็นการสาธิตสิ่งเดียวกัน -
ป้อนข้อมูล
สมมติว่าข้อมูลที่เราป้อนคือ −
Number : 15161718
ผลผลิต
ผลลัพธ์ที่ต้องการจะเป็น −
The result is : 8
อัลกอริทึม
Step 1 - START Step 2 – Declare two integer values namely my_count and my_input. Step 3 - Read the required values from the user/ define the values Step 4 – Using a for loop, divide the input value by 10 until the number is reduced to its lowest possible value. Increment the counter value each time. Step 5- Display the counter value as result Step 6- Stop
ตัวอย่างที่ 1
ที่นี่ ผู้ใช้ป้อนอินพุตตามข้อความแจ้ง คุณสามารถลองใช้ตัวอย่างนี้ในเครื่องมือกราวด์ของเรา
.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int my_count , my_input;
my_count = 0;
System.out.println("Required packages have been imported");
Scanner my_scanner = new Scanner(System.in);
System.out.println("A reader object has been defined ");
System.out.print("Enter the number : ");
my_input = my_scanner.nextInt();
for (; my_input != 0; my_input /= 10, ++my_count) {
}
System.out.println("The number of digits in the given input is: " + my_count);
}
} ผลลัพธ์
Required packages have been imported A reader object has been defined Enter the number : 15161718 The number of digits in the given input is : 8
ตัวอย่างที่ 2
ในที่นี้ มีการกำหนดจำนวนเต็มก่อนหน้านี้ และเข้าถึงและแสดงค่าบนคอนโซล
public class Main {
public static void main(String[] args) {
int my_count = 0, my_input;
my_count = 0;
my_input = 15161718;
System.out.println("The number is defined as " +my_input);
for (; my_input != 0; my_input /= 10, ++my_count) {
}
System.out.println("The number of digits in the given input is: " + my_count);
}
} ผลลัพธ์
The number is defined as 15161718 The number of digits in the given input is: 8