代码作曲家工作室

时间:2017-06-09 23:13:32

标签: c code-composer

所以问题是:在C中编写一个程序,使其包含一个计算给定整数的三次幂的函数。它应该使用你的函数计算1到10之间数字的三次幂,结果应该保存在一个数组中。

这就是我所拥有的(下图)。我在输出行= powerOfThree(int i + 1);中继续从CCS收到错误。错误说“预期表达”。我不确定我做错了什么。

#include<msp430.h>     

long int powerOfThree(int a);
long int arrayOfTen[10];
int powers = 3;
int output;
int i;
int temp;

int main(void) {
    WDTCTL = WDTPW | WDTHOLD;   // Stop watchdog timer

    for (i = 0; i <= 10; i++)
    {
        output = powerOfThree(int i+1);
        arrayOfTen[i] = output;

        return output;
    }
}

long int powerOfThree(int a)
{
    int result = a*a*a;
    return result;
}

2 个答案:

答案 0 :(得分:2)

以上代码有以下错误:

  • 在行output = powerOfThree(int i+1);中存在语法/语义错误。您应该将其更改为output = powerOfThree(i+1);
  • for循环中的条件部分应从i<=10更改为i<10
  • 返回return output;语句不应该在循环内。
  • 如果您希望函数powerOfThree(int a)返回long int,则函数原型应为long int powerOfThree(long int a)或类型along int以防止数据错误。

以下是更正后的代码:

注意:对优化进行了一些更改,即删除不必要的变量。

#include<msp430.h>     

long int powerOfThree(long int a);
long int arrayOfTen[10];
int i;

int main(void) {
    WDTCTL = WDTPW | WDTHOLD;   // Stop watchdog timer

    for (i = 0; i < 10; i++)
    {
        arrayOfTen[i] = powerOfThree(i+1);
    }
    return 0;
}

long int powerOfThree(long int a)
{
    long int result = a*a*a;
    return result;
}

答案 1 :(得分:0)

以下提议的代码:

  1. 干净地编译
  2. 被修改为在linux上运行
  3. 将所有内容声明为long int,以避免转换/溢出问题。
  4. 执行所需的功能。
  5. 现在是代码

    //#include <msp430.h>
    #include <stdio.h>
    
    #define MAX_NUM 10
    
    long int powerOfThree(long a);
    
    int main(void)
    {
        long int arrayOfTen[ MAX_NUM ];
        //WDTCTL = WDTPW | WDTHOLD;   // Stop watchdog timer
    
        for ( long i = 0; i < MAX_NUM; i++)
        {
            arrayOfTen[i] = powerOfThree(i+1);
            printf( "%ld to the third power is %ld\n", i+1, arrayOfTen[i] );
        }
    }
    
    long int powerOfThree(long a)
    {
        long result = (long)a*a*a;
        return result;
    }
    

    建议代码的输出是:

    1 to the third power is 1
    2 to the third power is 8
    3 to the third power is 27
    4 to the third power is 64
    5 to the third power is 125
    6 to the third power is 216
    7 to the third power is 343
    8 to the third power is 512
    9 to the third power is 729
    10 to the third power is 1000