C++ cin 无法读取其中包含 0 的整数

C++ cin can't read in integers with 0 in them

我在上 hacker运行k,我 运行 遇到了一个很奇怪的问题。问题是"You are given an integer N. Find the digits in this number that exactly divide N (division that leaves 0 as remainder) and display their count. For N=24, there are 2 digits (2 & 4). Both of these digits exactly divide 24. So our answer is 2."。这是我的解决方案:

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
    int t, count;

    cin >> t;
    for (int i = 0; i < t; i++) {
        int n, copy;
        cout << "i: " << i << " ";
        cin >> n;
        cout << "n: " << n << " ";
        copy = n;
        count = 0;
        while (copy > 0) {
            if (n % (copy % 10) == 0)
                count++;
            copy = copy/10;
        }
        cout << "\n" << count << "\n";
    }  
    return 0;
}

t为测试用例数,n为待测个数。我可以毫无问题地将我想要的任何数字输入 t。但是,如果我在 n 中输入一个带零的数字,则会出现浮点异常错误。错误发生在第二个 cout 语句之前。其他数字工作正常(例如,1024 给出错误,但 1124 没问题)。我 运行 黑客运行k 网站上的这段代码。有人可以解释一下这是怎么回事吗?

您不能 mod 除以 0。尝试重新设计您的算法,以避免尝试执行该操作。也许检查 copy % 10 == 0 然后跳过这种情况。它是 floating point exception 而不是 divide by zero exception 的原因在 this stack exchange post

中有描述

您不能 mod 某些内容为 0。检查以确保副本不为零。

浮点异常通常发生在尝试进行非法算术运算时。 (检查 this)在您的示例中,您最终将执行模 0,这是未定义的行为。大多数运行时都会因某种运行时错误而退出。 这是 gdb 在 运行 您的代码上给出的输出,输入如下:

1 10

Program received signal SIGFPE, Arithmetic exception.
0x0000000000400920 in main () at a.cpp:21
21              if (n % (copy % 10) == 0)

尝试改造你的算法,这样你就不会这样做了。

(我建议学习调试工具并运行你的代码通过它们来捕获此类问题)

关于为什么没有打印该行,那是因为 cin 和 cout 的大多数实现都是基于缓冲区的(阅读 this 以了解有关缓冲 i/o 的更多信息)。如果您在 cout 之后添加了一个 "std::endl",您可能已经看到了输出。或者您可以使用 std::cerr 来输出调试信息。 std::cerr 标准对冲水有更严格的要求。在您的情况下,在可以刷新缓冲区之前,应用程序已终止。

当您输入任何号码时,您的代码将正常工作。没有任何 0 数字。您的代码中的问题是您试图将数字除以 0。

       **if (n % (copy % 10) == 0)**

在这种情况下,当我们输入任何带有 0 作为数字的 no 时,(copy%10) 的值变为 0.Thus 它试图将 n 除以 0,从而引发浮点异常错误。 像这样更改您的代码:

声明一个名为 'r' 的新变量。这将在我们得到 0 作为 digit.Thus 时阻止命令的执行,程序将 运行 正常

while(copy!=0)
        {`enter code here`
            r=copy%10;
            if(r!=0)
            {
                if(n % r==0)
                count++;
            }
            copy=copy/10;
        }
        cout<<count<<endl;