2288. 价格减免
题目链接:2288. 价格减免
代码如下:
class Solution
{
public:
string discountPrices(string sentence, int discount)
{
// stringstream默认按照空格分隔字符串
stringstream ss(sentence);
string res, word;
// 一边分割,一边加到答案中
while (ss >> word)
{
if (!res.empty())
{
res += ' ';
}
if (word.size() > 1 && word[0] == '$' &&
all_of(word.begin() + 1, word.end(), ::isdigit))
{
stringstream s;
double price = stoll(word.substr(1, word.size() - 1)) *
(1.0 - discount / 100.0);
// 想要保留数据的有效位数,需要用到setprecision() /
// cout.precision()函数
// 想要保留n为小数,需要加上cout.setf(ios::fixed); 或者cout <<
// fixed或者cout<<setiosflags(ios::fixed)
s << fixed << setprecision(2) << '$' << price;
res += s.str();
} else
{
res += word;
}
}
return res;
}
};