简体   繁体   English

我的程序中出现 segsigv 错误的原因是什么?

[英]what can be the cause of segsigv error in my program?

I am quite new to coding and I was trying to solve a problem in which we would be given a number of test cases (say n) and an integer (say k).我对编码很陌生,我试图解决一个问题,在这个问题中,我们将获得许多测试用例(比如 n)和 integer(比如 k)。 So for each test case, a new integer(say a) will be given for which we have to find how many numbers (say sum) is divisible by k.所以对于每个测试用例,将给出一个新的整数(比如 a),我们必须找到有多少数字(比如总和)可以被 k 整除。

#include <iostream>
#include <cmath>
using namespace std;

int main()
{
    int n,k,sum;
    scanf("%d",n);
    scanf("%d",k);
    while(n>0)
    {
        int a;
        scanf("%d",a);
        if(a%k==0)
        {
            sum++;
        }
        n--
    }
    printf("%d",sum);
    return 0;
}

First, you provide the address of the variable when scanning with scanf :首先,您在使用scanf扫描时提供变量的地址:

scanf("%d", &n);
scanf("%d", &k);
scanf("%d", &a);

Also, initialise sum :另外,初始化sum

sum = 0;

Second, this is C++, so use cin and cout instead:其次,这是 C++,所以请改用cincout

std::cin >> n >> k;
std::cin >> a;

std::cout << sum;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM