c - 预期标识符或 '('

标签 c header-files

我想编写一个程序,通过定义一个名为 power(k) 的函数来计算 nk 幂。然后我想在同一个项目下的另一个文件中使用它输出一个3^k的表格,其中k的范围是0-9。但是当我尝试编译代码时出现错误。

如果您能指出我的错误,我将不胜感激。

//  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 函数隔离在另一个文件中。

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;
}

power_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。

关于c - 预期标识符或 '(',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33697186/

相关文章:

c - 使用c从计算机读取和打印文本文件

c++ - wmain 和 main 有什么区别?

ruby - 使用 rvm 安装 ruby​​ 头文件

c++ - 在每个类中包含相同的标题

c - 使用openssl(C语言)去除解密结果中的污垢

c - 多维数组模式访问

c++ - 使用 skbuff 头文件。

ios - XCode 中子项目的 header 搜索路径

c - 如何在项目中预定义头文件路径

java - 使用JNA从java crash VM调用c,谁能告诉我为什么会这样?