我想编写一个程序,通过定义一个称为的函数来计算的k
能力。然后,我想在同一项目下的另一个文件中使用它来输出3 ^ k的表,其中的范围是0-9。但是,当我尝试编译代码时出现错误。n
power(k)
k
如果您能指出我的错误,我将不胜感激。
// main.c
// #9-product of n
//
// Created by Leslie on 11/13/15.
// Copyright © 2015 Jiahui. All rights reserved.
//
#include <stdio.h>
int n;
long product;
int main(int argc, char *argv[])
{
long power(int k);
int k;
printf("Please input the number n and k\n");
scanf("%d%d",&n,&k);
product=power(k);
printf("the product is %ld\n",product);
}
long power(int k)
{
product=1;
int i;
for (i=1;i<=k;i++)
{
product=product*n;
}
return product;
}
第二个程序:
#include <stdio.h>
#include "main.c"
extern long power(int k);
for(i=1;i<=9;i++)
{
printf("%d\t",power(k));
}
我不太清楚同一项目下的另一个文件仅能打印3的幂,但是这很可能是您的功课。
无论如何,我认为重点在于查看如何包含文件,因此我也将幂函数隔离在另一个文件中。
power_calculator.c将分别接受两个参数{number}和{power}。
这是您可以执行的操作:
power_calculator.c
// power_calculator {n} {k}
// Calculates {n}^{k}
#include <stdio.h>
#include <stdlib.h>
// #include <math.h>
#include "math_power.h"
int main (int argc, char *argv[])
{
// two parameters should be passed, n, and k respectively - argv[0] is the name of the program, and the following are params.
if(argc < 3)
return -1;
// you should prefer using math.h's pow function - in that case, uncomment the #import <math.h>
//printf("%f\n", power(atof(argv[1]), atof(argv[2])));
// atof is used to convert the char* input to double
printf("%f\n", math_power(atof(argv[1]), atof(argv[2])));
return 0;
};
math_power.h
#ifndef _MATH_POWER_H_
#define _MATH_POWER_H_
double math_power(double number, double power);
#endif
math_power.c
#include "math_power.h"
double math_power(double number, double power){
double result = 1;
int i;
for( i = 0; i < power; i++ ){
result*=number;
}
return result;
}
powers_of_three.c
#include <stdio.h>
#include "math_power.h"
int main (int argc, char *argv[])
{
int i;
// here is your range 0-9
for(i = 0; i < 10; i++)
printf("%f\n", math_power(3, i));
return 0;
};
要编译powers_of_three.c或power_calculator.c,请记住包括math_power.h和math_power.c。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句