输入两位小数的英语单词,转化为两位小数。C++
时间: 2024-05-07 12:20:08 浏览: 112
c++小数转二进制.cpp
你可以使用 C++ 标准库中的 `std::stringstream` 类来实现这个功能。以下是一个示例代码:
```c++
#include <iostream>
#include <string>
#include <sstream>
int main() {
std::string word = "three point fourteen";
double number = 0.0;
std::stringstream ss(word);
std::string current_word;
while (ss >> current_word) {
if (current_word == "zero") {
number += 0.0;
} else if (current_word == "one") {
number += 1.0;
} else if (current_word == "two") {
number += 2.0;
} else if (current_word == "three") {
number += 3.0;
} else if (current_word == "four") {
number += 4.0;
} else if (current_word == "five") {
number += 5.0;
} else if (current_word == "six") {
number += 6.0;
} else if (current_word == "seven") {
number += 7.0;
} else if (current_word == "eight") {
number += 8.0;
} else if (current_word == "nine") {
number += 9.0;
} else if (current_word == "ten") {
number += 10.0;
} else if (current_word == "eleven") {
number += 11.0;
} else if (current_word == "twelve") {
number += 12.0;
} else if (current_word == "thirteen") {
number += 13.0;
} else if (current_word == "fourteen") {
number += 14.0;
} else if (current_word == "fifteen") {
number += 15.0;
} else if (current_word == "sixteen") {
number += 16.0;
} else if (current_word == "seventeen") {
number += 17.0;
} else if (current_word == "eighteen") {
number += 18.0;
} else if (current_word == "nineteen") {
number += 19.0;
} else if (current_word == "twenty") {
number += 20.0;
} else if (current_word == "thirty") {
number += 30.0;
} else if (current_word == "forty") {
number += 40.0;
} else if (current_word == "fifty") {
number += 50.0;
} else if (current_word == "sixty") {
number += 60.0;
} else if (current_word == "seventy") {
number += 70.0;
} else if (current_word == "eighty") {
number += 80.0;
} else if (current_word == "ninety") {
number += 90.0;
} else if (current_word == "hundred") {
number *= 100.0;
} else if (current_word == "thousand") {
number *= 1000.0;
} else if (current_word == "million") {
number *= 1000000.0;
}
}
std::cout << std::fixed << std::setprecision(2) << number << std::endl;
return 0;
}
```
在这个示例代码中,我们使用 `std::stringstream` 类来将输入的字符串 `word` 分解成一个个单词,然后判断每个单词对应的数字大小,并进行累加。最后使用 `std::fixed` 和 `std::setprecision` 来保留两位小数输出结果。
阅读全文