【问题标题】:Printing the digits of a number from left to right linewise从左到右逐行打印数字的数字
【发布时间】:2021-05-02 11:03:03
【问题描述】:

问题陈述是:

  1. 您必须显示数字的位数。
  2. 将“n”作为输入,即必须显示数字的数字。
  3. 按行打印数字的数字。
#include<iostream>
#include<cmath>

using namespace std;
 
int main(){
    int n;
    cin>>n;
    int nod = 0;
    int temp = n;
    while(temp != 0){
        temp = temp / 10;
        nod++;
    }
    int  div = (int)pow(10, nod - 1);
    while(div != 0){
        int dig = n / div;
        cout<<dig<<endl;
        n = n % div;
        div = div / 10;
    }
    return 0;
}

对于输入 65784383,预期输出为:

6

5

7

8

4

3

8

3

但是,程序的输出与预期不符。哪里出错了?

【问题讨论】:

  • 实际输出是多少?与预期有何不同?
  • 在这里按预期工作godbolt.org/z/qxhh1Y3s3
  • 不要在整数问题中使用pow 或其他浮点函数。 (许多像这样的问题都是专门设计的,这样做会导致问题。)

标签: c++ loops math


【解决方案1】:

也许你得到了错误的输出,我不知道,你没有说为什么你认为代码有问题。

我确实在这里得到了正确的输出:https://godbolt.org/z/xsTxfbxEx

但是,这是不正确的:

int  div = (int)pow(10, nod - 1);

pow 不适用于整数。我建议您阅读documentationthis,并考虑将浮点数截断为整数时会发生什么。

要打印用户给出的数字的逐行数字,您只需要这样:

#include <iostream>
#include <string>
int main() {
    std::string input;
    std::cin >> input;
    for (const auto& c : input) std::cout << c << "\n";
}

也许你认为这是作弊并坚持做数学。然后从后到前收集数字并以相反的顺序打印,这更简单:

#include <iostream>
#include <vector>
int main() {
    int n;
    std::cin >> n;
    std::vector<int> digits;
    while (n) {
        digits.push_back(n % 10);
        n /= 10;
    }
    for (auto it = digits.rbegin(); it != digits.rend(); ++it){
        std::cout << *it << "\n";
    }
}

PS:不要像这里那样使用 c 风格的演员表

 int  div = (int)pow(10, nod - 1);
           //^^

其实这里是多余的,因为给int分配一个浮点数已经做了截断。不过,通常也应避免使用 c 风格的演员表。据我所知,它们被允许的唯一原因是向后兼容。如果你确实需要投射,你应该使用static_cast。大多数情况下,c 风格的转换只是使编译器警告或错误静音,并隐藏代码中的问题。

【讨论】:

    猜你喜欢
    • 2012-05-27
    • 2017-02-21
    • 2017-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多