需要编写一个至少接受 4 位数字 (3453) 并打印出来的程序:"Three thousands four hundreds 5 tens and 3 ones"
Need to write a program that takes in at least 4 digits (3453) and prints out: "Three thousands four hundreds 5 tens and 3 ones"
我认为我走在正确的轨道上并且拥有我需要的所有元素,但我不太确定如何使用类/令牌,并且可能还有其他一些格式错误的东西。
#include <string>
#include <iostream>
#include <vector>
using namespace std;
class token {
public:
int value;
string unit;
}
int main() {
token t;
vector<token> v;
string unit = ""
cin>>x;
while (x!=0) {
t.value=x%10;
if (unit==" "}
t.unit = "ones";
else if (unit == "ones")
t.unit = "tens"
else if (unit = "tens")
t.unit = "hundreds"
else if (unit = "hundreds")
t.unit = "thousands"
v.pushback(t);
x=x/10;
}
v_t.push_back("zero")
v_t.push_back("one")
v_t.push_back("two")
v_t.push_back("three")
v_t.push_back("four")
v_t.push_back("five")
v_t.push_back("six")
v_t.push_back("seven")
v_t.push_back("eight")
v_t.push_back("nine")
cout<< "This is ";
for(int i = v.size()-1; i>=0, i--) {
cout<<v_t[v[i].value]<<" "<< v[i].unit << " "}
}
我在这里得到的所有东西都取自我的笔记,但排列顺序不同。当我尝试运行它时,我收到错误消息:"新类型可能未在新类型中定义"
编译错误很多,为了解决第一个错误,将分号放在类的末尾:
class token {
public:
int value;
string unit;
};
对于第二个,在单位声明的末尾添加一个分号:
string unit = "";
第三,定义"x":
int x;
第四,将"}"改为")":
if (unit==" ")
对不起,还有很多。在所有语句的末尾添加分号以开始。
是在这里打错了还是您忘记了所有分号? 除此之外,您还编写了用于比较unit
和"tens"
unit = "tens"
? 不应该是unit == "tens"
吗? 并检查空字符串if( unit = " " )
替换为if( unit.empty() )
在这个作业中,我不会使用std::vector
,而是使用固定长度的数组。
用C语言术语(表示思想):
struct Text_Entry
{
unsigned int value; // Don't deal with negatives with words.
const char * const text;
};
// Here's the table
struct Text_Entry conversion_table[] =
{
{0, "zero"},
{1, "one"},
{2, "two"},
//...
{10, "ten"},
{11, "eleven"},
//...
{20, "twenty"},
{30, "thirty"},
{40, "forty"},
};
编译器将在程序启动之前为您加载表,无需在每种情况下都使用 push_back
。 value
字段允许您按任意顺序排列条目。
如果允许,请首选std::map
.
不要对每个组合都使用表格。 例如,21 将使用条目 20 和条目 1。 同样适用于 135。
呵呵。