首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

c标题

2013-04-20 
c题目题目如下:编写函数void written_amount(unsigned int amount,char *buffer)它把amount表示的值转换

c题目
题目如下:编写函数
              void written_amount(unsigned int amount,char *buffer);
它把amount表示的值转换为单词形式,并储存于buffer中。这个函数可以在一个打印支票的程序中使用。例如,如果amount的值是16312,那么buffer中存储的字符串应该是
              SIXTEEN THOUSAND THREE HUNDRED TWELVE
有些值可以用两种不同的方法进行打印,例如,1200可以是ONE THOUSAND TWO HUNDRED或TWELVE HUNDRED。你可以选择一种你喜欢的模式。 
代码如下,不知道哪里错了,刚学的东西,很多不理解,可能有不要的代码,如果可以简写代码页帮忙看下,谢谢~
#include<stdio.h>
#include<string.h>
#include<math.h>
#define B 1000000000
#define M 1000000
#define T 1000
#define H 100
char *unit(int n);
char *teen(int n);
char *ty(int n);
char *nchar(int n);
void amount_string(int n, char *buffer);
static char *number_string1[10] = {"zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
 "nine"};
static char *number_string2[10] = {"ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", 
 "eighteen", "ninteen"};
static char *number_string3[8] = {"twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"};
int kk[4] = {B, M, T, H};
char *number_string4[4] = {" billion", " million", " thousand", " hundred"};
main(){
int n;
scanf("%d", &n);
char buf[100] = "", *buffer;
buffer = buf;
amount_string(n, buffer);
}
void amount_string(int n, char *buffer){
int i = 0;
int b = 0;
char buf[] = "";
buffer = buf;
if(n == 0){
puts(unit(0));
strcat(buf, unit(0));
}
else{
for(i = 0; i < 3; i++){
b = n / kk[i];
if(b != 0){
strcat(strcat(buf, nchar(b)), number_string4[i]);
n = n % kk[i];
if(n != 0){
strcat(buf, " and ");
}
}
}
}
puts(buffer);
}
char *unit(int n){
return number_string1[n];
}
char *teen(int n){
return number_string2[n - 10];
}
char *ty(int n){
return number_string3[n - 2];
}
char *nchar(int n){ //n是一个1000以下的数值 
char gg[] = "";
char *g;
g = gg;
int lll = 0, k = 0, temp = 0;
if(n >= H){
strcat(strcat(gg, unit(n / H)), " hundred");
lll = n % H;
if(lll != 0){
strcat(gg, " and ");
if(lll >= 20){
temp = lll / 10;
strcat(gg, ty(temp));
k = lll % 10;
if(k != 0){
strcat(strcat(gg, "-"), unit(k));
}
}
else if(lll >= 10){
strcat(gg, teen(lll));
}
else{
strcat(gg, unit(lll));
}
}
}
else if(n >= 20){
temp = n / 10;
strcat(gg, ty(temp));
k = n % 10;
if(k != 0){


strcat((strcat(gg, "-")), unit(k));
}
}
else if(n >= 10){
strcat(gg, teen(n));
}
else if(n > 0){
strcat(gg, unit(n));
}
else{
strcat(gg, unit(n));
}
return g;
} c?*?数组
[解决办法]
致命错误:amount_string和nchar函数中的buf和gg数组定义没有长度,会导致崩溃。
另外,你假定n为某一个值,例如9,然后自己读一下程序,或者画个流程图,看看程序是如何运行的,再去改正实现上的错误。
[解决办法]
http://www.codeproject.com/Articles/286999/Generic-Number-to-from-Word-Converter

热点排行