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
620 views
in Technique[技术] by (71.8m points)

floating point - Finding nth power of integer m through C program without pow()

C program to find nth power of integer m without pow().

Input:

m=3 n=2
output:
9.000

Tests to validate the program works as expected!

  1. For negative M
Input : -2  3
output : -8.000
  1. For negative N
Input : 2  -3  
output : 0.125000
  1. For negative M and N
Input : -2  -3
output : -0.125000

However I am not getting the desired output

void main() 
{

    signed int m, n;
    int i;
    float p;
    clrscr();
    printf("Enter the number and its power (exponent)
");
    scanf("%d%d",&m,&n);
    p=1;
    if (n==0)
    {
        printf("%d raised to %d is: %f",m,n,p);
    }

    if (n>0)
    {
        for( i = 0 ; i < n ; i++ )
            p*=m;
        if(m>0)
            printf("%d raised to %d is: %f",m,n,p); 
        if(m<0) 
            printf("%d raised to %d is: %f",m,n,-p); 
    }

    if (n<0)

    {
        n=-n;
        for( i = 0 ; i < n ; i++ )
            p*=m;
        if(m>0)
            printf("%d raised to %d is: %f",m,-n,1/p);
        if(m<0)
            printf("%d raised to %d is: %f",m,-n,-(1/p)); 
    }
    getch(); 
}

Can u kindly provide the correct program for the test cases?

I can't declare signed float as it is giving an error.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

The code for negatives is incorrect. You cannot just blindly negate the result when the base m is negative. image, but image. Also, you're not printing anything if m is zero!

And ints are signed by default so signed int is noise. floats are signed too; but here you could as well use a double for more precision. The return value of main should be int.

Therefore the fixed code would be (add nonstandard clrscrs and getchs to your taste ;):

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

int main() 
{
    int m, n, i;
    double p = 1.0;
    printf("Enter the number and its power (exponent)
");
    scanf("%d%d",&m,&n);

    if (n==0) {
        printf("%d raised to %d is: %f",m,n,p);
    }

    else if (n > 0) {
        for(i = 0; i < n; i++)
            p*=m;
        printf("%d raised to %d is: %f",m,n,p); 
    }

    else { // n < 0
        n = -n;
        for (i = 0 ; i < n ; i++)
            p*=m;
        printf("%d raised to %d is: %f", m, -n, 1 / p);
    }
}

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

...