【发布时间】:2013-04-03 09:19:41
【问题描述】:
这是一个用 c++ 编写的程序,来自这个 Write code to convert given number into words (eg 1234 as input should output one thousand two hundred and thirty four) 问题,我修改为将数字转换为单词。
在我的程序中,我没有重复使用 cout,而是创建了一个 ostream 对象 out 并将返回值放入 out。
这是程序
#include<iostream>
using namespace std;
ostream & expand(int);
int main()
{
int num;
cin>>num;
cout<<expand(num);
}
ostream & expand(int value)
{
ostream &out;
out<<"";
const char * const ones[21] = {"zero", "one", "two", "three","four","five","six","seven",
"eight","nine","ten", "eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen",
"eighteen","nineteen"};
const char * const tens[10] = {"", "ten", "twenty", "thirty","forty","fifty","sixty","seventy",
"eighty","ninety"};
if(value<0)
{
out<<"minus "<<expand(-value);
}
else if(value>=1000000){
out<<expand(value/1000000)<<" million";
if(value % 1000000)
{
out<<" "<<expand(value % 1000000);
}
}
else if(value>=1000)
{
out<<expand(value/1000)<<" thousand";
if(value % 1000)
{
if(value % 1000 < 100)
{
out << " and";
}
out << " " <<expand(value % 1000);
}
}
else if(value >= 100)
{
out<<expand(value / 100)<<" hundred";
if(value % 100)
{
out << " and "<<expand (value % 100);
}
}
else if(value >= 20)
{
out << tens[value / 10];
if(value % 10)
{
out << " " << expand(value % 10);
}
}
else
{
out << ones[value];
}
return &out;
}
但是,编译时出现以下错误。
In function 'std::ostream& expand(int)':
Line 13: error: 'out' declared as reference but not initialized
compilation terminated due to -Wfatal-errors.
请帮帮我。
我尝试设置ostream &out=cout;,最后设置return out。但我得到cout<<expand(111234) 的以下结果。
one0x8050884 hundredeleven and 0x80508840x8050884 thousandtwo0x8050884 hundredthirtyfour 0x8050884 and 0x8050884 0x80508840x8050884
【问题讨论】:
-
你的问题是什么>?编译问题(在这种情况下,您将 wayyyy 发布到很多代码中)?还是你得到的输出?
-
这是我现在得到的输出......
-
感谢您的回答@AndyProwl。但是,使用您建议的更改,我没有得到正确的输出。你能帮我编辑我的代码建议更改,以便我能得到正确的答案吗?