陷阱: 用最大的n位数-1(数字太大可能产生越界) 应该采用字符串模拟数字自加! 代码如下: #include<iostream> using namespace std; int IsMax(char *number) { int nLength = strlen(number); int CarryBit = 0; bool ret = false; for (int i = nLength-1; i >= 0; i--) { int nSum = number[i] - ‘0‘ + CarryBit; if (i == nLength - 1) ++nSum; if (nSum >= 10) { if (i == 0) ret = true; else { nSum -= 10; CarryBit = 1; number[i] = ‘0‘ + nSum; } } else { number[i] = ‘0‘ + nSum; break; } } return ret; } void Print1ToN(int n) { if (n <= 0) return; char *number = new char[n+1]; memset(number, ‘0‘, n); number[n] = ‘\0‘; while (!IsMax(number)) { cout << number << " " ; } } int main() { Print1ToN(10); getchar(); return 0; } 输出部分可以做一些优化将 从第一个不为0的开始输出。
原文地址:http://10955910.blog.51cto.com/10945910/1750216