简体   繁体   English

字符没有使用 atoi() 添加为整数?

[英]Chars not adding as ints using atoi()?

I'm new to C. I have a very silly question, but I can't figure out this very simple bug in my code for generating combinations.我是 C 的新手。我有一个非常愚蠢的问题,但我无法弄清楚我的代码中用于生成组合的这个非常简单的错误。


#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void combinations (int v[], int start, int n, int k, int maxk) {
        int i;

        if (k > maxk) {
                
                for (i=1; i<=maxk; i++) {
                  int sum = 0;
                  sum += v[i];
                  printf("%d", sum);
                }
                
                printf ("\n");
                return;
        }
        
        for (i=start; i<=n; i++) {
                v[k] = i;
                combinations (v, i+1, n, k+1, maxk);
        }
}

int main (int argc, char *argv[]) {
        int v[100], n, k;
        n = atoi (argv[1]);
        k = atoi (argv[2]);
        combinations (v, 1, n, 1, k);
        exit (0);
}

If you run the code above using ./main 5 3 , you'll get the following:如果您使用./main 5 3运行上面的代码,您将得到以下内容:

123
124
125
134
135
145
234
235
245
345

What I was trying to do was print out the sum of the integer representations, not the concatenated characters - for instance, the first line should be 6 , not 123 .试图做的是打印出整数表示的总和,而不是连接的字符 - 例如,第一行应该是6 ,而不是123 Unfortunately, I'm getting a weird error when ever I use atoi() on the line sum += v[i];不幸的是,当我在sum += v[i];行上使用atoi()时,我遇到了一个奇怪的错误sum += v[i]; , eg sum += atoi(v[i]); ,例如sum += atoi(v[i]); throws an error.引发错误。 I know I can't really use atoi() because I don't have a pointer, but I'm not sure how to resolve this problem.我知道我不能真正使用atoi()因为我没有指针,但我不确定如何解决这个问题。 Using int(v[i]) doesn't throw an error, but it also doesn't fix the problem.使用int(v[i])不会引发错误,但也不能解决问题。

I'd greatly appreciate if someone could 1) tell me why atoi() isn't appropriate here/how I'm using it wrong and 2) how I can get each element of each combination to be treated as an integer.如果有人可以 1) 告诉我为什么atoi()在这里不合适/我如何使用它是错误的,以及 2) 我如何将每个组合的每个元素都视为一个整数,我将不胜感激。

The following loop is resetting sum on every iteration, so all it's doing is adding v[i] to 0 each time.以下循环在每次迭代时重置sum ,因此它所做的就是每次将v[i]添加到0 It's also printing sum on every iteration, rather than once at the end:它还在每次迭代时打印sum ,而不是在最后打印一次:

for (i=1; i<=maxk; i++) {
    int sum = 0;
    sum += v[i];
    printf("%d", sum);
}
printf ("\n");

Just change it to:只需将其更改为:

int sum = 0;
for (i=1; i<=maxk; i++) {
    sum += v[i];
}
printf("%d\n", sum);

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

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