计算功率的结果,并没有math.h中碱 [英] Calculating the result of a power and a base without math.h

查看:122
本文介绍了计算功率的结果,并没有math.h中碱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的大学,我被要求创建一个程序,要求两个输入用户。一个是基,而另一个是一个数字的功率。我不允许使​​用文件math.h 只循环。

At my university I was asked to create a program that asks the user for two inputs. One is the base and the other is the power of a number. I am not allowed to use math.h only loops.

这是我的code迄今:

This is my code thus far:

#include <stdio.h>

int main() {
    int base;
    printf(" Please enter the base: ");
    scanf("%d", &base);

    int power;
    printf(" Please enter the power: ");
    scanf("%d", &power);

    printf("\n%d ^ %d is the same as...\n\n", base, power);

    printf(" %d", base);

    int reps;
    int number;
    for(reps = base; reps <= power; reps += 1) {
        printf("* %d ", base);
    }

    for(number; number <= power;number += 1) {
        int result = base * base;
        for (result; number <= power; result = base * result) {
            result = result * base;
            printf("\n or  %d", result);
        }
    }


    return 0;
}

请帮助我。我很失落,我想哭:(这不是问题。

Please help me. I am so lost and I feel like crying :( not that it matters.

推荐答案

(你的主要问题是,你使用的是未初始化变量;这样做,在C的行为的未定义的)

(Your main issue is that you are using an uninitialised variable; the behaviour of doing that in C is undefined.)

但是,让我们返工答案。要做的第一件事就是实际功率的功能的所有输入和输出分开。至于该功能,我会把我喜欢的方式插入的理解答案池,你会通过仔细工作,并了解它。

But let's rework the answer. The first thing to do is to separate the actual power function from all the input and output. With regards to that function, I'll put my favourite way into the answer pool on the understanding that you'll work through it carefully and understand it.

您可以通过王牌平方使用名为幂技术这个问题的:

You can ace this problem using a technique called exponentiation by squaring:

int getPower(int base, int power/*must be non-negative*/)
{
    int ret = 1;
    while (power){
        if (power & 1){ /*this means the current value of `power` is odd*/
            ret *= base;
        }
        power >>= 1; /*ToDo - figure this out with your debugger*/
        base *= base;
    }
    return ret;
}

该方法在 https://en.wikipedia.org/wiki/Exponentiation_by_squaring

这篇关于计算功率的结果,并没有math.h中碱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆