通过测试c中的和或组合的组合形成的奇怪输出

时间:2015-05-04 15:08:06

标签: c

我的简单代码有问题。我希望获得EX 4的所有产品和特定数量的总和 - > 0 + 4 1 + 3 2 + 2 3 + 1 4 + 0。为了总和所以我做了这个代码:

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

 typedef struct{
 unsigned int x;
 unsigned int y;
 }str;

 const int MAX = 200000;

 int main(int argc,char *argv[]){
 int s=atoi(argv[1]);
 if(s<0 || s>MAX){
    printf("errore nummero incompatibile!\n");
    exit(-1);       
 }
 str sum;
 int n=MAX;
 for (sum.x=0;sum.x<n;sum.x++){
    for (sum.y=0;sum.y<n;sum.y++){
        if(strcmp(argv[2],"+")==0){
            if(sum.x+sum.y==s){
                printf("%d + %d = %d\n",sum.x,sum.y,s);
            }
        }else{
            if(sum.x*sum.y==s){
                printf("%d * %d = %d\n",sum.x,sum.y,s);
            }
        }
    }
 }
 exit(-1);
 }

argv [1]是要测试的数字,而argv [2]是模式(Sum或product)

这是产品输出44 *:

1 * 44 = 44
2 * 22 = 44
4 * 11 = 44
11 * 4 = 44
22 * 2 = 44
44 * 1 = 44
25266 * 169990 = 44
33998 * 126330 = 44
42110 * 101994 = 44
50532 * 84995 = 44
50997 * 84220 = 44
63165 * 67996 = 44
67996 * 63165 = 44
84220 * 50997 = 44
84995 * 50532 = 44
101994 * 42110 = 44
126330 * 33998 = 44
167378 * 179622 = 44
169990 * 25266 = 44
179622 * 167378 = 44`

它给出了正确的输出但是它开始给出更多的数字。每次运行它们都是一样的。这是什么,我怎么能阻止这个?

1 个答案:

答案 0 :(得分:3)

你正在遍历每个数字,直到MAX,导致你一路上溢出(See vitaut's answer for the explaination of your issue and how to prevent overflow in your case, he explained that very well.)。这不是必要的。当你试图找到2个整数乘法的每个组合时,你只需要迭代直到所述数字,或者如果数字太大则必须迭代。 尝试改变

  int n=MAX;

by:

 int n = s;
 if (s > MAX)
    int n=MAX;