因为标题暗示我的算法用于将数值转换为字符串存在问题。我可以达到一定数量,但一旦我达到100美元,程序就会崩溃。我对一些价值观也差不多几美分,所以我想知道我能做些什么来改变它。
这是我的头文件
#include <sstream>
#include <iostream>
#include <iomanip>
#include <string>
#include <string.h>
using namespace std;
class TextVersionOfNumber
{
private:
double amount;
public:
string getTextVersionOfNumber();
void setAmount(double);
};
这是我的.cpp文件(这是算法所在的位置)
#include "TextVersionOfNumber.h"
string TextVersionOfNumber::getTextVersionOfNumber()
{
string upto20[20] = { "", "one", "two", "three", "four",
"five", "six", "seven", "eight", "nine", "ten",
"eleven", "twelve",
"thirteen", "fourteen", "fifteen", "sixteen", "seventeen",
"eighteen", "nineteen" };
string ten_ninety[10] = { "", "", "twenty", "thirty", "forty",
"fifty", "sixty", "seventy", "eighty", "ninety" };
double _amount1 = (int)amount;
double _amount2 = (amount - _amount1) * 100;
string str_one = "";
if (_amount1 <= 19)
{
str_one = upto20[(int)_amount1];
}
else
{
int tens = _amount1 / 10;
int ones = _amount1 - (tens * 10);
str_one = ten_ninety[tens] + upto20[ones];
}
string str_two = "";
if (_amount2 <= 19)
{
str_two = upto20[(int)_amount2];
}
else
{
int tens = _amount2 / 10;
int ones = _amount2 - (tens * 10);
str_two = ten_ninety[tens] + upto20[ones];
}
string ret_val = "$ " +str_one + " and " + str_two + " cents";
system("pause");
return ret_val;
};
void TextVersionOfNumber::setAmount(double _amount)
{
amount = _amount;
};
这是测试人员档案(这是我老师提供的)
// Chapter 12-- Assignment 14: Check Writer
// This program can convert a dollar and cents amount given in
// numerical form to a word description of the amount.
#include <iostream>
#include <iomanip>
#include <string>
#include <string.h>
using namespace std;
#include "TextVersionOfNumber.h"
// Assume a maximum amount of $10,000
int main()
{
string date = "03/05/2016", payee = "Michael Wille";
TextVersionOfNumber checkAmount;
double testAmounts[] = { 0, .01, .25, 12, 12.45, 19, 19.02,
19.45, 20, 20.45,
34, 56.78, 100, 109, 119.78,
450, 678.90, 1000, 1009.45, 1056,
1234, 1567.98, 9999, 9999.99 };
for (int i = 0; i < sizeof(testAmounts) / sizeof(double); i++)
{
double an_amount = testAmounts[i];
checkAmount.setAmount(an_amount);
cout << setprecision(2) << fixed;
cout << setw(60) << right;
cout << "Date: " << date << endl;
cout << "Pay to the order of: " << payee << "\t\t\t";
cout << "$" << an_amount << endl;
cout << checkAmount.getTextVersionOfNumber() << endl;
cout << "---------------------------------------------------------------------\n";
}
system("pause");
return 0;
}
答案 0 :(得分:2)
else
{
int tens = _amount1 / 10;
int ones = _amount1 - (tens * 10);
str_one = ten_ninety[tens] + upto20[ones];
}
如果amount = 100,则tens将等于10,您将其用作10个元素数组的引用,这些元素超出数组范围。你的代码可以工作&lt; 100,但一旦它达到一百,它将不再起作用。