gpt4 book ai didi

c++ - 将美元金额转换为字符串

转载 作者:行者123 更新时间:2023-11-28 07:16:54 25 4
gpt4 key购买 nike

作业是这样的(取自某网站)

Write a program that displays a simulated paycheck. Theprogram should ask the user to enterthe date, the payee's name,and the amount of the check. It should then display a simulatedcheck with he dollar amount spelled out, as shown here.

Date: 11/24/2007

Pay to the Order of: JohnPhillips $1920.85

One thousand nine hundred twenty and 85 cents

我已经完成了很多,但问题在于如何打印出文本美元金额。这是我到目前为止所拥有的(注意,这只是属于类的函数)

#include <iostream>
#include <iomanip>
#include <string>
#include <cstdlib>
#include "TextVersionOfNumber.h"


using namespace std;

string TextVersionOfNumber::convertNumberToText()
{

string one_19[] = {"", "one", "two", "three", "four",
"five", "six", "seven", "eight", "nine", "ten",
"eleven", "twelve",
"thirteen", "fourteen", "fifteen", "sixteen", "seventeen",
"eighteen", "nineteen"};

string twenty_90[] = {"","","twenty","thirty","forty",
"fifty", "sixty", "seventy", "eighty", "ninety"};


double amount;
int a = amount/1000;
int b = (amount/100) - (a*10);
int c = (amount/10) - (a*100) - (b*10);
int d = amount - (a*1000) - (b*100) - (c*10);
int cents = (amount*100) - (a*100000) - (b*10000) - (c*1000) - (d*100);

if (a >= 1)
amount_string = one_19[a] + " thousand " + one_19[b] + " hundred "
}

void TextVersionOfNumber::setAmount(double DollarAmount)
{
DollarAmount = amount;
}

if 语句是我打算开始做一个大的嵌套 if block 的地方,但我的老师说“我不会接受一个带有 if 语句而不是数组处理的程序!需要使用决策结构来实现这个逻辑; 但是使用 10-20 个“if”语句是 Not Acceptable !”

很明显,我应该使用这种称为“数组处理”的逻辑,但我对它是什么一无所知,到目前为止,我的搜索只出现了初始化和各种填充和填充的方法访问一个数组。问题是:数组处理到底是什么,我如何使用它来完成这段代码?不要为我完成代码,我通过示例学习最好。

好的,我做到了,遇到了一些问题,修复了它,现在一切正常了。我调用她,她说可以使用一些 if 语句,但她不希望我只使用 if 语句来完成所有事情。所以,谢谢大家!

最佳答案

好吧,你可以获得每个数字的第一位数字并通过一些数组运行它:

int thousands = amount / 1000;
int hundreds = amount % 1000 / 100;
int tens = amount % 100 / 10;
int ones = amount % 10;
int decimal = amount - static_cast<int>(amount) * 100;
//takes out the decimal and multiplies by 100
final_string = th_string[thousands] + hu_string[hundreds] + te_string[tens] + o_string[ones] + to_string(decimal) + "cents";

当然你必须实现_string:我不会为你做硬件

关于c++ - 将美元金额转换为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20086796/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com