程序打印数组中的所有数字,向后打印
Program prints all digits from array, prints backwards
我正在制作一个程序,打印数组中的所有数字(以整数形式输入),它可以工作,但数字是向后打印的,我不知道如何反转它们。有人能帮忙吗?
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
void explode(int number,int array[])
{
while (number > 0) {
int digit = number % 10;
cout << digit << 'n';
number /= 10;
}
}
int main()
{
int digits[100];
int numdigits;
int n;
cout << "Enter number: ";
cin >> n;
// numdigits = explode(n,digits);
cout << "[";
while (n > 0) {
int digit = n % 10;
n /= 10;
digits[digit] = digit;
cout << digits[digit];
}
cout << "]" << endl;
}
您只需要使用reverse()
从<algorithm>
反转数组。
代码:
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <cmath>
using namespace std;
int array_c = 0;
void explode(int number,int array[])
{
while (number > 0) {
int digit = number % 10;
number /= 10;
array[array_c++] = digit;
}
}
int main()
{
int digits[100];
int numdigits;
int n;
cout << "Enter number: ";
cin >> n;
explode(n,digits);
reverse(digits,digits+array_c);
cout << "[";
for(int i = 0; i < array_c; ++i)
cout<<digits[i];
cout << "]" << endl;
}
的使用
digits[digit] = digit;
是不对的。你可能打算使用
digits[numdigits] = digit;
你可以把工作分成两步来解决你的问题。在第一步中,存储数字。在第二步中,打印数字。
int numdigits = 0;
while (n > 0) {
cout << "n: " << n << endl;
int digit = n % 10;
n /= 10;
digits[numdigits++] = digit;
}
// Make sure to print them in reverse order.
cout << "[";
for ( ; numdigits > 0; )
{
cout << digits[--numdigits];
}
cout << "]" << endl;
相关文章:
- 打印数字图案
- 错误含义;以二进制形式打印数字
- 列中打印数字时如何避免打印垃圾?
- C++ 在地板函数之后以十六进制打印数字
- C/C++ - 用于按顺序打印数字的 sem_t 类型的单个信号量
- 仅打印数字的小数位
- 在 c++ 列中打印数字
- 为什么 al_draw_textf() 打印数字而不是存储在字符串变量中的字母
- 如何使用递归按从 1 到 n 的升序打印数字,其中 n 在该函数的参数中给出
- 该程序如何反向打印数字的数字?
- C 以升级循环时按升序打印数字
- 如何使用C 中的printf打印数字列表
- 为什么使用算术而不是bitest以二进制形式打印数字更快
- 为什么不按升序打印数字
- 为什么这段代码不能正常打印数字?
- 尝试优化和理解打印数字除数的递归函数的运行时
- 我希望程序打印数字 0 到 99,但是当我运行代码时,我看到 100 行 99
- C++程序仅在打印数字时才有效
- 只有在没有重复数字的情况下才打印数字
- 不能算出这个按数字顺序打印数字的c++小程序的最后一个