在编程中,主程序可以通过多种方式驱动子程序。以下是一些常见编程语言中主程序调用子程序的方法:
C语言
主程序通过函数调用的方式来调用子程序。首先需要声明子程序,然后在主程序中使用函数名加括号的方式来调用子程序。例如:
```c
include
// 声明子程序
void subprogram();
int main() {
printf("主程序\n");
// 调用子程序
subprogram();
return 0;
}
// 定义子程序
void subprogram() {
printf("子程序\n");
}
```
Python
子程序通常以函数形式存在,在主程序中通过函数名加括号的方式调用。例如:
```python
add_student.py
def add_student(name, age):
print(f"添加学生 {name} ({age}岁) 成功")
display_students.py
def display_students():
students = [("张三", 18), ("李四", 20), ("王五", 19)]
for name, age in students:
print(f"学生 {name} ({age}岁)")
delete_student.py
def delete_student(name):
print(f"删除学生 {name} 成功")
main.py
from add_student import add_student
from display_students import display_students
from delete_student import delete_student
def main():
while True:
调用子程序
add_student("张三", 18)
display_students()
delete_student("李四")
if __name__ == "__main__":
main()
```
Java
子程序通常定义在类中,通过类的实例调用方法。例如:
```java
// MyClass.java
public class MyClass {
public void myMethod() {
System.out.println("子程序执行");
}
}
// Main.java
public class Main {
public static void main(String[] args) {
MyClass myObject = new MyClass();
// 调用子程序
myObject.myMethod();
}
}
```
C++
子程序通常定义在独立的文件中,通过函数名加括号的方式调用。例如:
```cpp
// subprogram.h
void subprogram();
// main.cpp
include "subprogram.h"
include
int main() {
std::cout << "主程序" << std::endl;
// 调用子程序
subprogram();
return 0;
}
// subprogram.cpp
include "subprogram.h"
include
void subprogram() {
std::cout << "子程序" << std::endl;
}
```
MATLAB
子程序通常定义在独立的脚本文件中,通过脚本文件名加括号的方式调用。例如:
```matlab
% add_student.m
function add_student(name, age)
disp(sprintf('添加学生 %s (%d岁) 成功', name, age));
end
% display_students.m
function display_students()
students = {'张三', 18; '李四', 20; '王五', 19};
for i = 1:length(students)
disp(sprintf('学生 %s (%d岁)', students{i}{1}, students{i}{2}));
end
end
% delete_student.m
function delete_student(name)
disp(sprintf('删除学生 %s 成功', name));
end
% main.m
from add_student import add_student
from display_students import display_students
from delete_student import delete_student
function main()
while true
add_student('张三', 18)
display_students()
delete_student('李四')
end
end
```