问题描述
输入:
<$ p $ m = 3 n = 2
输出:
9.000
测试验证程序是否按预期运行!
- 对于负数M
lockquote
输入:-2 3
输出:-8.000
- 对于负数N
然而,我没有得到所需的输出
void main()
{
signed int m,n;
int i;
float p;
clrscr();
printf(输入数字及其权力(指数)\ n);
scanf(%d%d,& m,& n);
p = 1;
if(n == 0)
{
printf(%d提升到%d是:%f,m,n,p);如果(n> 0)
{
for(i = 0; i p * = m;
if如果(m> 0)
printf(%d提升到%d是:%f,m,n,p),
。如果(m printf(%d提升到%d是:%f,m,n,-p),
;
if(n
{
n = -n;
for(i = 0; i p * = m;如果(m> 0)
printf(%d上升到%d是:%f,m,-n,1 / p),
。 (m printf(%d提升到%d是:%f,m,-n, - (1 / p));
}
getch();
}
您能否为测试用例提供正确的程序?
我不能声明有符号浮点数,因为它给出错误。
底片的代码不正确。当基础 m 为负数时,不能盲目否定结果。
,但。此外,如果 m 为零,则不会打印任何内容!
$ b
int s是默认签名的,所以 signed int 是噪音。 float s也被签名;但是在这里你可以使用 double 来获得更高的精度。 main 的返回值应该是 int 。
因此,固定的代码将是(添加非标准 clrscr s和 getch s以符合您的口味):
#include< stdio.h>
#include< stdlib.h>
int main()
{
int m,n,i;
double p = 1.0;
printf(输入数字及其权力(指数)\ n);
scanf(%d%d,& m,& n);
$ b $ if(n == 0){
printf(%d提升到%d是:%f,m,n,p);
}
else if(n> 0){
for(i = 0; i p * = m;
printf(%d提升到%d是:%f,m,n,p);
}
else {// n< 0
n = -n;
for(i = 0; i p * = m;
printf(%d提升到%d是:%f,m,-n,1 / p);
}
}
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!
- For negative M
- For negative N
- For negative M and N
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)\n"); 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.
The code for negatives is incorrect. You cannot just blindly negate the result when the base m is negative., but . 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)\n"); 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); } }
这篇关于通过没有pow的C程序找到整数m的n次幂()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!