ปัญหา
โปรแกรมสำหรับพิมพ์ชื่อคอลัมน์ของ Excel ที่ตรงกับหมายเลขคอลัมน์ที่กำหนด (ค่าจำนวนเต็ม) ผู้ใช้ต้องป้อนหมายเลขจำนวนเต็มตามหมายเลขที่กำหนดเพื่อพิมพ์หมายเลขคอลัมน์ excel
วิธีแก้ปัญหา
วิธีแก้ปัญหาในการพิมพ์ชื่อคอลัมน์ Excel ที่สอดคล้องกับหมายเลขคอลัมน์ที่กำหนดในภาษา C ได้อธิบายไว้ด้านล่าง -
ตัวอย่างที่ 1
เรามาดูตัวอย่างกัน
1 -> A 2 -> B ... 26 -> Z 27 -> AA 28 -> AB ...
ตัวอย่างที่ 2
- ข้อมูล อินพุต เป็นดังนี้ −
number = 3 number = 27 number = 151
- ผลลัพธ์ เป็นดังนี้ −
Excel column title: C Excel column title: AA Excel column title: EU
ตัวอย่าง
ต่อไปนี้เป็นโปรแกรม C เพื่อ พิมพ์ชื่อคอลัมน์ Excel ที่ตรงกับหมายเลขคอลัมน์ที่กำหนด −
#include <stdio.h>
static char *convert_To_Excel_Title(int column_no){
if (column_no <= 0) {
return "";
}
char *result = malloc(1024);
int len = 0;
do {
result[len++] = ((column_no - 1) % 26) + 'A';
column_no = (column_no - 1) / 26;
} while (column_no > 0);
result[len] = '\0';
int i, j;
for (i = 0, j = len - 1; i < j; i++, j--) {
char c = result[i];
result[i] = result[j];
result[j] = c;
}
return result;
}
int main(void){
int n;
printf("enter the integer1:");
scanf("%d",&n);
printf("Column Number n = %d", n);
printf("\nExcel column title: %s\n\n ",convert_To_Excel_Title(n));
printf("enter the integer2:");
scanf("%d",&n);
printf("\nColumn Number n = %d", n);
printf("\nExcel column title: %s\n\n ",convert_To_Excel_Title(n));
printf("enter the integer3:");
scanf("%d",&n);
printf("\n\nColumn Number n = %d", n);
printf("\nExcel column title: %s ",convert_To_Excel_Title(n));
return 0;
} ผลลัพธ์
เมื่อโปรแกรมข้างต้นทำงาน มันจะให้ผลลัพธ์ดังต่อไปนี้ −
enter the integer1:23 Column Number n = 23 Excel column title: W enter the integer2:12 Column Number n = 12 Excel column title: L enter the integer3:69 Column Number n = 69 Excel column title: BQ