| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 525 人关注过本帖
标题:K&R《C语言编程》第26页 函数问题
只看楼主 加入收藏
oat
Rank: 1
等 级:新手上路
帖 子:7
专家分:0
注 册:2012-7-15
结帖率:50%
收藏
已结贴  问题点数:10 回复次数:5 
K&R《C语言编程》第26页 函数问题
我写了如下的代码:
程序代码:
#include <stdio.h>

int power(int m, int n);

/* test power function */
int main(int argc, const char * argv[])
{
    int i;

 
    for (i=0; i<10; ++i)
        printf("the power of 2  by %d is %d \n", i, power(2,i) );
        printf("the power of -3 by %d is %d \n", i, power(-3,i));

 
    return 0;
}

/* power function: raise base to n-th power; n>=0 */
int power(int base, int n)
{
    int i, p;
    p=1;
    for (i=1; i<=n; ++i)
        p = p * base;
    return p;
}

但却得到如下结果:
程序代码:
the power of 2  by 0 is 1
the power of 2  by 1 is 2
the power of 2  by 2 is 4
the power of 2  by 3 is 8
the power of 2  by 4 is 16
the power of 2  by 5 is 32
the power of 2  by 6 is 64
the power of 2  by 7 is 128
the power of 2  by 8 is 256
the power of 2  by 9 is 512
the power of -3 by 10 is 59049

而我期待的结果是:
程序代码:
the power of 2  by 0 is 1
the power of -3 by 0 is 1
the power of 2  by 1 is 2
the power of -3 by 1 is -3
the power of 2  by 2 is 4
the power of -3 by 2 is 9
the power of 2  by 3 is 8
the power of -3 by 3 is -27
the power of 2  by 4 is 16
the power of -3 by 4 is 81
the power of 2  by 5 is 32
the power of -3 by 5 is -243
the power of 2  by 6 is 64
the power of -3 by 6 is 729
the power of 2  by 7 is 128
the power of -3 by 7 is -2187
the power of 2  by 8 is 256
the power of -3 by 8 is 6561
the power of 2  by 9 is 512
the power of -3 by 9 is -19683

请教我的代码在哪里写错了呢?

谢谢!
搜索更多相关主题的帖子: 编程 C语言 color 
2012-08-11 10:21
demonleer
Rank: 9Rank: 9Rank: 9
等 级:贵宾
威 望:10
帖 子:483
专家分:1225
注 册:2012-6-4
收藏
得分:5 
你知道大括号这东西是干什么用的么
2012-08-11 10:25
cnfarer
Rank: 16Rank: 16Rank: 16Rank: 16
等 级:版主
威 望:179
帖 子:3330
专家分:21157
注 册:2010-1-19
收藏
得分:5 
循环体用{}

★★★★★为人民服务★★★★★
2012-08-11 10:51
cnfarer
Rank: 16Rank: 16Rank: 16Rank: 16
等 级:版主
威 望:179
帖 子:3330
专家分:21157
注 册:2010-1-19
收藏
得分:0 
循环体用"{}"

★★★★★为人民服务★★★★★
2012-08-11 10:52
oat
Rank: 1
等 级:新手上路
帖 子:7
专家分:0
注 册:2012-7-15
收藏
得分:0 
noted with many thanks!
2012-08-11 11:44
oat
Rank: 1
等 级:新手上路
帖 子:7
专家分:0
注 册:2012-7-15
收藏
得分:0 
呵呵,典型菜鸟错误。谢谢!

修正代码:
程序代码:
#include <stdio.h>

int power(int m, int n);

/* test power function */
int main(int argc, const char * argv[])
{
    int i;

 
    for (i=0; i<10; ++i)
    {
        printf("the power of 2  by %d is %d \n", i, power(2,i) );
        printf("the power of -3 by %d is %d \n", i, power(-3,i));
    }

 
    return 0;
}

/* power function: raise base to n-th power; n>=0 */
int power(int base, int n)
{
    int i, p;
    p=1;
    for (i=1; i<=n; ++i)
        p = p * base;
    return p;
}

2012-08-11 11:46
快速回复:K&R《C语言编程》第26页 函数问题
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.021483 second(s), 7 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved