阿摩線上測驗 登入

申論題資訊

試卷:105年 - 105年身障特考四等程式設計概要#50187
科目:程式設計
年份:105年
排序:0

申論題內容

一、請寫一個由兩個函式構成的 C 語言程式,舉例說明何謂區域變數與全域變數。 (20 分)

詳解 (共 5 筆)

詳解 提供者:王煜閔
#include #include int total(int number1, int number2); int totalValue=0; //此為全域變數 int main(void) { int number1, number2;// 此為區域變數 scanf("%d %d", &a,&b); total(number1, number2);//函式呼叫 return 1; } int total(int number1, int number2) { total = number1 + number2; printf("%d", total); return 1; }
詳解 提供者:Zhe Zhen Hong
#include(iostream.h) #include(stdlib.h) int a,b; //全域變數 int add(int m,int n) { int sum; //區域變數 return sum; } void main(void){ int a=10,b=20; //區域變數 add(&a,&b); }
詳解 提供者:ddd7788989

#include #include int main () { int Global_variable = 0; // printf("%d", Area_variable); 這一處將無法正常編譯 printf("%d", Global_variable); } void function () { int Area_variable = 0; printf("%d", Global_variable); printf("%d", Area_variable); }

詳解 提供者:hchungw
在C語言中,全域變數是在函式外部定義的變數,它們在程序的整個執行過程中都是可見的,而區域變數是在函式內部定義的變數,它們只在定義它們的函式內部可見。以下是一個簡單的示例程序,展示了全域變數和區域變數的使用。
#include <stdio.h>
// 全域變數定義
int globalVar = 10;
// 函式原型宣告
void demoFunction();
void anotherFunction();
int main() {
    printf("在 main() 中的全域變數初始值: %d\n", globalVar);
    
    // 調用函式,展示區域變數和修改全域變數
    demoFunction();
    
    printf("回到 main() 中,全域變數的值: %d\n", globalVar);
    
    // 再次調用另一個函式,展示全域變數的值未被局部變數影響
    anotherFunction();
    
    return 0;
}
// 函式定義
void demoFunction() {
    // 區域變數定義
    int localVar = 20;
    
    printf("在 demoFunction() 中的區域變數: %d\n", localVar);
    
    // 修改全域變數的值
    globalVar = 30;
    
    printf("在 demoFunction() 中修改後的全域變數: %d\n", globalVar);
}
void anotherFunction() {
    printf("在 anotherFunction() 中的全域變數: %d\n", globalVar);
}
 

在這個程序中,globalVar是一個全域變數,它在main函式、demoFunction函式和anotherFunction函式中都是可見的。當demoFunction函式被調用時,它首先打印了一個區域變數localVar的值,然後修改了全域變數globalVar的值。注意到即使globalVar的值在demoFunction中被修改,這個修改對於程序中的其他部分(如anotherFunction)也是可見的。

相反,localVar是一個區域變數,它只在demoFunction函式中可見。當demoFunction函式執行完畢後,localVar就不再存在,而且它對其他函式(包括anotherFunction和main)沒有任何影響。

詳解 提供者:顏存偉

public static PI=3.14; //全域函式 任一函式均可取用此變數 void int function( int a){ int num=10; //兩函式之間有某個同名變數 但各自保有原設定值 cout<