c - 如何在没有“pow”的情况下实现 a^b?
问题描述
我需要编写一个函数来计算 a^b 但我不允许使用pow
. 有任何想法吗?我搞不清楚了。看起来问题现在很重要......在某个地方,我的特点是 vys。因此,如果我在 main 中设置 vys=1,我会在输出中得到 1..
#include <stdio.h>
#include <time.h>
#include <math.h>
#include <unistd.h>
void multiplied(int b, int n)
{
int i=1, vys=1;
while (i<=n)
{
vys *=b;
i++;
}
return vys;
}
main(void)
{
int b=0, n=0, vys=1;
printf("Give numbers b and n but they must be in interval <0,10>!\n");
scanf("%d %d", &b, &n);
if ((b < 0 || b>10) || (n<0 || n>10))
{
printf("Numbers are not in interval <0,10>!\n");
}
else
{
printf("Number is in interval so i continue...\n");
sleep(2);
vys= multiplied(&b, &n);
printf("%d", vys);
}
解决方案
让我们明确一点。
首先,这
void multiplied(int *b, int *n)
返回一个int,所以这么说。
int multiplied(int *b, int *n)
接下来,您在 main 中初始化变量:在此处执行相同操作。
int i, vys;
像这样:
int i=1, vys=1;
现在让我们看一下循环:
while (i<=n)
{
vys=*b**b;
i++;
}
就目前而言,您vys
在循环中一遍又一遍地设置某些东西。您想乘以,例如 2,然后是 2*2,然后是 2*2*2,......如果您想要 2 的幂:
while (i<=n)
{
vys *= *b;
i++;
}
现在,您不需要传递指针。
int multiplied(int b, int n)
{
int i=1, vys=1;
while (i<=n)
{
vys *= b;
i++;
}
return vys;
}
编辑:
调用函数时要注意:
main(void)
{
int b=0, n=0, vys;
//input and checking code as you have it
multiplied(&b, &n); //<---- return ignored
printf("%d", vys); //<-- print uninitialsed local variable
}
改变你最后两行:
vys = multiplied(&b, &n); //<---- return captured
printf("%d", vys); //<-- print returned variable
编辑2:
随着在函数中使用而不是指针的更改int
,传递整数而不是它们的地址:
vys = multiplied(b, n); //<---- pass the ints not their addresses
printf("%d", vys); //<-- print returned variable, which should vary now
推荐阅读
- spring-cloud-gateway - spring cloud gateway动态路由,一个路由错了,所有的路由都会错
- grafana - 不要使用 promQL 在 Grafana 中显示来自重新部署的 pod 的数据
- azure-aks - 如何创建 ClusterIP 服务?
- sharepoint-2013 - 使用 CSOM 管理 Sharepoint 2013 列表电子邮件设置
- angular - 如何在 Springboot Jar 中集成 Angular 7 应用程序?
- javascript - 使用 Wowjs JQuery 插件时出现滚动问题
- batch-file - XCopy 到带有提示符和通配符的路径
- r - 如何使用 highcharter 添加“标签”和“值”参数
- android - 反编译apk
- wordpress - Wordpress:如何从现有页面创建页面模板?