iT邦幫忙

2021 iThome 鐵人賽

DAY 29
1
Software Development

C 語言的簡單入門系列 第 29

【Day 29】函式(下)

昨天我們討論的函式,是沒有返回數值的函式,只是單純傳入參數做運算後,直接輸出。但我們更多時候會需要把參數傳入函式,會返回一個數值,再利用那個數值繼續做後續的計算。所以,今天會來講有返回數值的函式!

我們一樣先來看一段程式碼:

#include<stdio.h>
float square(float);
int main(){
	float n, answer;
	printf("Please input a number>>");
	scanf("%f", &n);
	answer = square(n);
	printf("\n");
	printf("The answer is %.3f", answer);
	return 0;
} 
float square(float a){
	float A;
	A = a*a;
	return A;
}

輸出結果:

程式說明:

  • float square(float); 這個一樣是函式宣告,和昨天的程式碼不同的是,昨天的程式碼沒有返回數值,所以返回數值型態為 void ,今天的程式碼是會返回數值的,返回數值型態為 float(第一個 float),而小括號 () 裡面的依然是傳入參數的型態,在這裡也是 float
  • 我們先看 square() 函式的部分:裡面有一行程式碼是 return A,這一行就是我們返回在函式內計算後的數值
  • 最後,來看一下主程式中使用函式的部分:answer = square(n);,這一行的意思就是,把經過函式計算後返回的值存在變數 answer 中,方便輸出。

我們也可以把程式碼修改一下:

#include<stdio.h>
float square(float);
int main(){
	float n;
	printf("Please input a number>>");
	scanf("%f", &n);
	printf("The answer is %.3f", square(n));
	return 0;
} 
float square(float a){
	return a*a;
}

上面程式碼中,我們更改了原本函式多宣告一個變數 的地方,讓函式直接返回輸入函數的平方。也更改了主程式中多宣告變數 answer 的地方,使程式碼更精簡!

明天,就讓我們來講講遞迴!


上一篇
【Day 28】函式(上)
下一篇
【Day 30】遞迴
系列文
C 語言的簡單入門30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言