ปัญหา
สำหรับตัวเลขที่กำหนด ให้พยายามหาช่วงที่มีตัวเลขนั้นอยู่
วิธีแก้ปัญหา
เรากำลังเรียนรู้วิธีหาช่วงของตัวเลข
ตรรกะที่เราใช้ในการหาช่วงคือ −
lower= (n/10) * 10; /*the arithmetic operators work from left to right*/ upper = lower+10;
คำอธิบาย
ให้หมายเลข n=45
ต่ำกว่า=(42/10)*10 // หารส่งคืนผลหาร
=4*10 =40
บน=40+10=50
ช่วง − ล่าง-บน − 40-50
ตัวอย่าง
ต่อไปนี้เป็นโปรแกรม C สำหรับ การพิมพ์ช่วงของตัวเลข −
#include<stdio.h>
main(){
int n,lower,upper;
printf("Enter a number:");
scanf("%d",&n);
lower= (n/10) * 10; /*the arithmetic operators work from left to right*/
upper = lower+10;
printf("Range is %d - %d",lower,upper);
getch();
} ผลลัพธ์
เมื่อโปรแกรมข้างต้นทำงาน มันจะให้ผลลัพธ์ดังต่อไปนี้ −
Enter a number:25 Range is 20 – 30
นี่คือโปรแกรม C อื่นสำหรับ การพิมพ์ช่วงของตัวเลข
#include<stdio.h>
main(){
int number,start,end;
printf("Enter a number:");
scanf("%d",&number);
start= (number/10) * 10; /*the arithmetic operators work from left to right*/
end = start+10;
printf("Range is %d - %d",start,end);
getch();
} ผลลัพธ์
เมื่อโปรแกรมข้างต้นทำงาน มันจะให้ผลลัพธ์ดังต่อไปนี้ −
Enter a number:457 Range is 450 – 460