C字符串练习题(6.3.1)

本文介绍了一个C语言程序,它从用户键盘输入一个不超过1000的正整数,然后将其转换为英文形式的字符串,如Ninehundredandfortyone。程序利用split_number函数和预定义的单词数组实现转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

编写一个程序,从键盘上读入一个小于1000的正整数,然后创建并输出一个字符串,说明该整数的值。例如,输入941,程序产生的字符串是“Nine hundred and forty one”。

#include<stdlib.h>
#include<string.h>
#include<stdio.h>

 
void split_number(int n, int* digits, int* count);

void split_number(int n, int* digits, int* count) {

	int i = 0;

	while (n > 0) {
		digits[i++] = n % 10;
		n /= 10;
	}

	*count = i;

}

int main() {
  

	char unit_to_word[][6] = { "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
    char ten_to_word[][8] = { "ten", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" };
	int digits[4];
	int count;

	char strNum[100];

	int num = 0;
	printf("Please enter an integer less than 1000 and greater than 0\n ");
	int result = scanf_s("%d",&num);

	split_number(num, digits, &count);

	if (count == 1) {

		char* str  = unit_to_word[digits[0]-1];
		strcpy_s(strNum, str);
	}
	else if(count == 2)
	{
		char* str = ten_to_word[digits[1]-1];
		strcpy_s(strNum, str);
		strcat_s(strNum, " ");
		if (digits[0] != 0) {
			strcat_s(strNum, sizeof(strNum), unit_to_word[digits[0] - 1]);
		}
	
	}
	else
	{
		char* str = unit_to_word[digits[2]-1];
		strcpy_s(strNum, str);
		strcat_s(strNum, " handred ");
		if (digits[1] != 0) {
			strcat_s(strNum, " and ");
			strcat_s(strNum,sizeof(strNum), ten_to_word[digits[1] - 1]);
		}
		strcat_s(strNum, " ");
		if (digits[0] != 0) {
			strcat_s(strNum, sizeof(strNum), unit_to_word[digits[0] - 1]);
		}

	}
	
	printf("The number you entered is converted to English is:\n %s\n\n", strNum);

    return 0;
   
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

幸福在路上wellbeing

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值