![](/img/trans.png)
[英]Getting an error in C saying that function definition is not allowed here before '{' token
[英]How to debug this error in C: function definition is not allowed here?
我是編程新手,正在參加edX的CS50(編程入門)課程。 我一直在嘗試編譯此C代碼,但始終會產生如下錯誤消息:
這是我一直嘗試編譯的代碼行:
#include <cs50.h>
#include <stdio.h>
#include <math.h>
int main (void)
{
bool valid_triangle (float a, float b, float c);
bool valid_triangle (float a, float b, float c)
{
// check positive values
if ( a <= 0 || b <= 0 || c <= 0 )
{
return false;
}
//check two sides are longer
if ( (a + b <= c) || (a+c <= b) || (b+c <= a))
{
return false;
}
//otherwise return true
return true;
}
}
有誰知道我做錯了什么以及如何解決此錯誤? 非常感謝!
以下建議的代碼:
現在,建議的代碼為:
//#include <cs50.h>
#include <stdio.h> // putc()
//#include <math.h>
#include <stdbool.h> // bool, true, false
bool valid_triangle (float a, float b, float c)
{
// check positive values
if ( a <= 0 || b <= 0 || c <= 0 )
{
return false;
}
//check two sides are longer
if ( (a + b <= c) || (a+c <= b) || (b+c <= a))
{
return false;
}
//otherwise return true
return true;
}
int main (void)
{
float a = 1;
float b = 2;
float c = 3;
if( valid_triangle (a, b, c) )
{
puts( "able to calculate triangle area" );
}
else
{
puts( "area of triangle cannot be calculated" );
}
}
編譯器錯誤消息是您最好的朋友,因此請充分利用它們。 在這里,您的錯誤消息triangle.c:9.6
告訴您您的錯誤在第9行。而且,它還會顯示字符串error: function definition is not allowed here.
在C語言(一種過程語言)中,不允許在其他函數內部使用函數定義。
要解決此問題,請在main()
函數之前定義您的函數,然后從您的main函數中調用valid_triangle
函數。 組織代碼的另一種方法是將有效的valid_triangle
原型放到main
函數之前,然后在main
函數的主體下面定義有效的valid_triangle
。
記住,main()函數是程序的入口點。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.