Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

a c program which calculating and printing the gcd and lcm of n numbers

My program should calculate and print the gcd and lcm of n numbers. First user will enter the number n. Then, user will enter the n many numbers and these numbers should assign an array. Lastly, gcd and lcm will be calculeted and printed.

I can not use the user-defined functions in my program. I know this is strange but it is a must.

I wrote my code. It calculates and prints the gcd correctly. But when it comes to lcm it prints meaningless numbers. Also the program don't start without enter 2 numbers. Can somebody tell me where my mistake is?

here is my code:

#include <stdio.h>
#include <stdlib.h>
#define max 100
int main()
{

    int n,i,ii, product,gcd,lcm,arr[max],j=1;

    printf(" How many numbers do you want to enter?
");
    scanf("%d ",&n);


    for(i=0;i<n;i++)
    {

        printf(" enter the %d. number: 
",(i+1));
        scanf("%d ",&arr[i]);

    }

    gcd = arr[0];


    while(j<n)
        {

        if(arr[j]%gcd==0){
                j++;

                         }

        else{

            gcd=arr[j]%gcd;
            }

       }
       
       
        printf("GCD of all numbers is %d 
", gcd);
        
        
        
        product=1;
        
        for(ii=0;ii<n;ii++){
            
            product=product*arr[i];
        }
        
        lcm=product/gcd;
        
        printf("LCM of all numbers is %d",lcm);
        
        

    return 0;
}

and here is an output of my program:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Also the program don't start without enter 2 numbers

Reason:

scanf("%d ",&n);

Here, there is extra space inside scanf. A space character in a scanf format causes it to explicitly read and ignore as many space characters as it can. So with scanf("%d ",&n); after reading a number, it will continue to read characters, discarding all whitespace until it sees a non-whitespace character on the input.

Remove the space in scanf statement. Use scanf("%d",&n);


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...