-
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
-
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))
-
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:
I'm not saying it's wrong, I just don't really understand it's meaning.
3. Are you sure this bit is right?
--
Mats