编程求解:
➢要求输入任一个三位正整数a,和任1-9之间的数字b,要求编程找出1-a之间所有带数字b和b的倍数的数字,并将这些数字打印出来。
➢例如,输入的是a=568,b=7, 则将1至568之间的所有带有7的数(如17, 27...) 和7的倍数(如14, 21...)的数字都输出在屏幕。
➢a和b要能任意输入
实现
#include<iostream>
#include< iomanip >
using namespace std;
int DigitCapacity(int x) //判断输入的是几位数
{
int y=0;
while(x)
{
x /= 10;
y++;
}
return y;
}
int LineBreak(int x) //每行输出8个数字后换行
{
if (x == 8)
{
cout << endl;
return 0;
}
else
return x;
}
int main()
{
int a, b, c, i, j;
c = 0;
//输入数字阶段
do {
cout << "Please enter a positive three-digit integer:" << endl;
cin >> a;
c = DigitCapacity(a);
} while (c != 3);
do {
cout << "Enter a positive single-digit integer between 1 and 9:" << endl;
cin >> b;
c = DigitCapacity(b);
} while (c != 1);
//输出到屏幕阶段
cout << "Between 1 and " << a;
cout << ", the number with " << b << " are:" << endl;
for (i = 1, j = 0; i <= a; i++)
{
j=LineBreak(j);
if(i%10==b)
{
cout << setw(8) << i; j++; continue; //continue能避免重复输出
//如a=333,b=3时,没有continue则333会输出3次
}
if(i/10%10==b)
{
cout << setw(8) << i; j++; continue;
}
if(i/100==b)
{
cout << setw(8) << i; j++; continue;
}
}
cout << endl<<"Between 1 and " << a;
cout << ", the numbers that are the multiple of " << b << " are:" << endl;
for (i = 0, j = 0; i <= a; i++)
{
j=LineBreak(j);
if (i % b == 0)
{
cout << setw(8) << i;
j++;
}
}
}