我正在编写一个 C++ 函数,它接受一个正数并返回一个包含其数字反转的数组。
#include <cmath>
#include <vector>
std::vector<int> digitize(unsigned long n) {
int x = 1;
for (int i = 1; n >= pow(10,i-1); ++i) { // Supposed to return the correct number of digits
x = i;
}
std::vector<int> result;
for (x; x > 0; --x) { // Takes the number of digits and begin assembling the array in reverse
result[x] = n / pow(10,x-1);
}
return result;
}
在编译过程中,它返回了警告,而且我很确定该函数还没有完成我想要做的事情。其中一个警告与
for (x; x > 0; --x)
循环有关(某些表达式未使用)。变量 x 不应该继承上一个循环中的值吗?
我尝试修改第二个循环以使用 i 而不是 x,但正如预期的那样,变量 i 的值和初始化没有从第一个循环中继承。
例如你可以这样做
#include <list>
#include <string>
#include <iostream>
auto to_string(std::uint64_t value)
{
std::list<char> result;
while( value > 0 )
{
result.push_front(static_cast<char>(value % 10) + '0');
value /= 10ul;
}
return std::string{result.begin(), result.end()};
}
int main()
{
std::cout << to_string(1234) << "\n";
std::cout << to_string(12340) << "\n";
}