Problem(again)

This is a discussion on Problem(again) within the C Programming forums, part of the General Programming Boards category; i wrote this program,there are some problems Code: #include <stdio.h> long int pow(int a,int b){ int x=0,y=1; while(x<b){ y*=a; x++;} ...

  1. #1
    Registered User
    Join Date
    Mar 2009
    Posts
    28

    Problem(again)

    i wrote this program,there are some problems
    Code:
    #include <stdio.h>
    
    
    long int pow(int a,int b){
        int x=0,y=1;
        while(x<b){
        y*=a;
        x++;}
        return y;}
    
    
    int rakam_top(long int a){
    	int x=10,y=0;
    	while((x<=a)&&(x%10==0)){
    		if (x==10){y+=a%x;}
    		y+=a/x;
    		x*=10;}
    	return y;}
    
    
    int main(){
    	int x,y;
    	long int z;
    	printf ("X raised to power of Y \n\n X=");
    	scanf ("%i",&x);
    	getchar();
    	printf ("\n Y=");
    	scanf ("%i",&y );
    	getchar();
    	z = pow(x,y);
    	printf("\n %i raised to the power %i = %ld \n",x,y,z);
    	printf("\n Digit sum= %i \n",rakam_top(z));
    	getchar();
    	return 0;}
    when i declare x=2 and y=15
    it finds the pow. right but Digit sum finds 3646/

    when i declare x=2 and y=100
    it return pow. 0

  2. #2
    Making mistakes
    Join Date
    Dec 2008
    Posts
    476
    Code:
    int rakam_top(long int a)
    {
        int result = 0;
        while (a / 10 > 0)
            result += a - (a / 10 * 10);
    
        return result;
    }
    2 ^ 100 = 10000000000000000........ in binary. The result is truncated, only the right bits are left. (Straight integer overflow, for every number 2 ^ n, where n is greater than a word (usually 32 bits))
    Last edited by Brafil; 04-20-2009 at 07:37 AM.

  3. #3
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    1. Please alter your style to not put the ending brace on the last line of code - put it on it's own line on the next line [I personally prefer to have the starting brace on a separate line TOO, but at the very least the ending brace should be on it's own line].

    2. What exactly does this part of your while statement do:
    Code:
    (x%10==0)
    I'm not saying it's wrong, I just don't really understand it's meaning.

    3. Are you sure this bit is right?
    Code:
    		y+=a/x;

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21