c++遇到以下技术问题,解决不了。注释请尽量详细。谢谢!
写一个名为PrtPyDigixSth的C++函数,将一个整数和打印输出的数字向后打印。假设参数总是非负的。如下表三个函数调用及其对应的输出。
void print_digits_backwards(int x)
{
if (x == 0) { cout << 0; return; }
while (x != 0)
{
cout << x % 10 << ' ';
x /= 10;
}
}
void print_digits_backwards(int num)
{
if (num == 0)
{
std::cout << 0;
}
else
{
while (num)
{
std::cout << num % 10 << ' ';
num /= 10;
}
}
std::cout << std::endl;
}
void PrtPyDigixSth(int val)
{
std::string c;
char a[20] = {};
sprintf_s(a,"%d",val);
int len = strlen(a);
for (int i = 0; i < len/2; ++i)
{
char temp = a[i];
a[i] = a[len - 1 - i];
a[len - 1 - i] = temp;
}
std::cout << a <<std::endl;
}
void func(int value)
{
std::string src = std::to_string(value);
for(int i=1;i<=src.length();++i)
std::cout << src[src.length() - i] << std::endl;
}
思路:转换成字符串 倒叙打印
void print_digits_backwards1(unsigned int value)
{
char strValue[1024] = {0};
itoa(value, strValue, 10);
for (int i = strlen(strValue) - 1; i >= 0; i--)
printf("%d ", strValue[i] - '0');
printf("\n");
}
思路:取余 打印,去掉最后一位循环到结束
void print_digits_backwards2(unsigned int value)
{
do{
printf("%d ", value % 10);
value /= 10;
} while (value > 0);
printf("\n");
}
可以用递归的方式
void PrtPyDigixSth(int x){
printf("%d",x % 10);
x = x / 10;
if ( x != 0 ) {
PrtPyDigixSth(x);
}
}
printf是函数。cout是ostream对象,和<<配合使用