各種言語で「独自関数」の作り方まとめ
プログラミングを続けていくと同じような処理を使いまわしたい時に、
ユーザ自身で独自の自作関数を作って効率化を図りたいことがありますよね。
今回はそんな各種開発言語における関数の作り方をまとめました。
perl
#!/usr/bin/perl
#
use strict;
use warnings;
my $num1 = 12;
my $num2 = 34;
my $total = total($num1, $num2);
print ("Total = ".$total."\n");
sub total {
my ($num1, $num2) = @_;
my $total = $num1 + $num2;
return $total;
}
php
<?php
$number1 = 12;
$number2 = 34;
$total = add($number1,$number2);
output($total);
function add($num1,$num2){
$num = $num1 + $num2;
return($num);
}
function output($num){
print($num);
}
python
#!/usr/bin/python3
number1 = 12
number2 = 34
def add(num1,num2):
num=num1+num2
return(num)
def output(num):
print(num)
total = add(number1,number2)
output(total)
ruby
#!/usr/bin/ruby
number1 = 12
number2 = 34
def add(num1,num2)
num = num1+num2
return(num)
end
def output(num)
print(num)
end
total=add(number1,number2)
output(total)
go
package main
import "fmt"
func main(){
var number1 int = 12
var number2 int = 34
var total int = add(number1,number2)
output(total)
}
func add(num1 int, num2 int) (num int) {
num = num1 + num2
return
}
func output(num int) {
fmt.Println(num)
return
}
java
public class Hello{
public static void main(String args[]){
int number1 =11;
int number2 =22;
int total = add(number1,number2);
System.out.println(total);
return;
}
static int add (int num1,int num2){
int num;
num = num1 + num2;
return num;
}
static int output (int num){
System.out.println(num);
return num;
}
}
c
#include <stdio.h>
int Add(int num1, int num2)
{
int num;
num = num1 + num2;
return num;
}
void Output(int num)
{
printf("Total= %d",num);
printf("\n");
}
int main()
{
int number1, number2, total;
number1 = 12;
number2 = 34;
total = Add(number1, number2);
Output(total);
}
c++
#include <iostream>
using namespace std;
int add(int num1, int num);
void output(int num);
int main(){
int number1 = 11;
int number2 = 22;
int total = add(number1,number2);
output(total);
return 0;
}
int add(int num1, int num2){
int num=num1+num2;
return num;
}
void output(int num){
cout << "Total=" << num << endl;
}