[英]Error when compiling in Code Composer Studio - Tiva C Series
[英]C code in code composer studio
所以問題是:用C編寫一個程序,使其包含一個計算給定整數的三次方的函數。 它應該使用您的函數計算1到10之間的數字的三次冪,並且結果應保存在數組中。
這就是我所擁有的(下)。 我不斷從CCS的output = powerOfThree(int i + 1);行收到錯誤消息。 錯誤顯示“期望表達式”。 我不確定自己在做什么錯。
#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;
}
上面的代碼具有以下錯誤:
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)
或強制轉換a
以long 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;
}
以下建議的代碼:
long int
以避免轉換/溢出問題。 現在的代碼
//#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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.