【问题标题】:Program does not work (leading zeroes)程序不起作用(前导零)
【发布时间】:2016-10-16 10:56:15
【问题描述】:

您必须编写一个迭代过程 write_digit(d,x),它接收一个数字 d 和一个自然数 x,并在标准输出 (cout) 中写入数字 d 的 x 倍。例如,调用 write_digit(3,5) 写入 33333,而调用 write_digit(5,3) 写入 555。

我对这段代码有疑问,它与前导零有关。例子: write_digit(0,3) -> 000 -> 我的输出:0(不足为奇)

如果允许我使用 iomanip,问题将在 1 分钟内解决

if (d == 0) cout << setw(x) << setfill('0') << "";

但是,我只能使用 iostream 和字符串。

#include <iostream>

using namespace std;

void write_digit(int d,int x) {
    int original_d = d; 
    for (int i = 1; i < x; ++i) d = d*10 + original_d;
    if (x == 0) cout << "";
    else cout << d;
}

int main () {
    int d,x;
    cin >> d >> x;
    write_digit(d,x);
}

【问题讨论】:

    标签: c++ formatting


    【解决方案1】:

    您完全使分配过于复杂,只需制作一个没有任何边缘条件的简单循环,它适用于任何数字,甚至适用于非数字。

    void write_digit(int d, int x) {
        for (int i = 0; i < x; ++i) // Loop x times
            std::cout << d;         // Output digit
        std::cout << '\n';          // Output newline
    }
    

    【讨论】:

    • 完全忘记了这种可能性,我傻了。
    猜你喜欢
    • 1970-01-01
    • 2014-06-18
    • 1970-01-01
    • 1970-01-01
    • 2018-06-25
    • 2018-04-06
    • 2019-10-31
    • 1970-01-01
    • 2017-03-28
    相关资源
    最近更新 更多