C++将int的每一位数提取到数组中

#include <iostream>
using namespace std;

int main() {

    int n;
    cin>>n;
    int n1=n;
    int count=1;
    //计算有多少位数
	while (n1 /= 10)
	{
		count++;   
	}
    int a[100] = { 0 };//用于存放int的每一位数
	for(int i = count-1; i >=0; i--) {
        //可以用  int i = 0; i <count; i++;这样会让高位变低位如123变为321
        a[i] = n % 10;//将每一位数放到数组中,n%10获得的是个位的数字
        n /= 10;//去除个位上的数字
	}
    //输出
    for(int i = 0; i < count; i++) {
		cout << a[i];

	}

}

        该方法是先求出int的位数大小,在根据int的位数大小进行运算,将int的每一位数放到数组中方便后续操作。

猜你喜欢

转载自blog.csdn.net/weixin_51265212/article/details/129371763