代码块程序读取一个数字并显示小于该数字且前 3 位相同的所有数字

问题描述 投票:0回答:1

我正在尝试编写一个代码块程序,该程序读取一个数字(输入)并显示所有小于给定数字且前三个相同数字的数字(输出)。

例如:对于 1400(输入),程序应显示:11,222,333,444,555,666,777,888 等(输出)

我尝试过的:


#include<iostream>



using namespace std;



int main () {



int n,x,i,z;



cin>>n;



    for(i=111;i<n-1;i++)



    x=i;



    while(z){



    int c=z%10;



    z=z/10;



        z=z*10+c;}



        if(z%10==z%100&&z%100==z%1000)




    cout<<z<<" ";




    return 0;

}

代码没有错误,如果我引入一个数字,输出为 0….

c++ line codeblocks digits
1个回答
0
投票

在使用

z
之前,您从未为其分配实际值,因此
while(z)
未定义。
(您是否将
z
x
混淆了?
x
被赋予了一个值,但从未使用过...)

但是,这看起来很像尝试教您从不同角度处理问题的练习之一。
在这种情况下,不同的角度是“我实际上知道这些数字是什么样的,所以也许我可以只打印有趣的数字,而不是在所有数字中搜索它们”。
这要快得多 - “有趣的”数字只是所有数字的一小部分 - 并且不需要太多聪明的算术。

一个简单的例子:

int main() {
    const int threes[] = {111, 222, 333, 444, 555, 666, 777, 888, 999};
    int limit = 0;
    std::cin >> limit;
    int left = limit;
    int factor = 1; // Will go 1, 10, 100, 1000, ...
    while (left > 110) {
        // This loops over the three-digit numbers.
        for (int i = 0; i < 9 && threes[i] * factor <= limit; i++) {
            // This loops over the "trailing" digits.
            for (int tail = 0;
                 tail < factor && threes[i] * factor + tail <= limit;
                 tail++) {
                std::cout << threes[i] * factor + tail << ' ';
            }
            std::cout << '\n';
        }
        left /= 10;
        factor *= 10;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.