iT邦幫忙

2023 iThome 鐵人賽

0
自我挑戰組

C語言精讀研習系列 第 35

在程式中段指定變數值

  • 分享至 

  • xImage
  •  

完整程式碼

#include <stdio.h>

int main(void){
	int coffee = 80;	//宣告變數並給初始值
	printf("咖啡原價一杯 %d\n", coffee);
	
	coffee = 100;		//第二次指定的值會蓋過第一個數值
	printf("咖啡漲為一杯 %d\n", coffee);
		
	return 0;
} 

輸出結果
https://ithelp.ithome.com.tw/upload/images/20240102/20160744URI7BmL8W0.png


指定變數時,也可指定為算式。如1 + 2 + 3 + ... + 10,這時程式會先求出算式的結果再指定給變數variable,呈現如下。

完整程式碼

#include <stdio.h>

int main(void){
	int variable;	//宣告整數型別變數
	//使用變數來承接1累加到10的總和
	variable = 1 +  2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10;	
	//先算出此式的結果,再指定給variable變數 
	
	printf("由 1 累加到 10 的總合為 %d", variable);
	
	return 0;
}

輸出結果
https://ithelp.ithome.com.tw/upload/images/20240102/20160744z6nAKcvUjU.png


參考資料:最新C程式語言


上一篇
宣告變數並給予其初始值
下一篇
整數、浮點數互相轉換
系列文
C語言精讀研習46
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言