Q1.りんごは50円、ばななは70円である。3つずつ買った時の合計金額を求めよ。
なお消費税は8%とする。
<?php $apple=50; $banana=70; $num=3; const TAX=1.08; ?> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>タイトル</title> </head> <body> <?php echo 'りんごを'.$num.'つ<br>'; echo 'ばななを'.$num.'つ<br>'; $result=floor((($apple*$num+$banana*$num))*TAX); echo '合計は'.$result.'円です'; ?> </body> </html>
Q2.身長と体重をフォームから入力し、BMIを求めるプログラムを作成せよ。
BMIは身長m/(体重kg*体重kg)で求められる。
●index.html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>BMI</title> </head> <body> <form action="result.php" method="post"> 身長<input type="number" name="height">cm<br> 体重<input type="number" name="weight">kg<br> <button type="submit">送信</button> </form> </body> </html>
●result.php
<?php
if(isset($_POST['height'])){
$height=(float)$_POST['height']/100;
$weight=(float)$_POST['weight'];
$bmi=round($weight/($height*$height),2);
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>BMI</title>
</head>
<body>
<?php
echo "BMIは{$bmi}です。\n";
?>
</body>
</html>
Q3.インチを入力するとセンチに変換するアプリを作成せよ。
Inch To cm
●index.html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>inch</title> </head> <body> <form action="result.php" method="post"> インチを入力:<input type="number" name="inch">インチ<br> <button type="submit">送信</button> </form> </body> </html>
●result.php
<?php
if(isset($_POST['inch'])){
$inch=(float)$_POST['inch'];
$cm=$inch*2.54;
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Inch</title>
</head>
<body>
<?php
echo "{$inch}インチは{$cm}です。\n";
?>
</body>
</html>
(別解:1枚のファイルで行う)
●inch.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Inch</title>
</head>
<body>
<?php
if(isset($_POST['inch'])){
$inch=(float)$_POST['inch'];
$cm=$inch*2.54;
echo "{$inch}インチは{$cm}です。\n";
}else{?>
<form method="post">
インチを入力:<input type="number" name="inch">インチ<br>
<button type="submit">送信</button>
<?php } ?>
</body>
</html>
Q4.数値を入力すると1からその数値までの和を求めるプログラムを作成せよ。
sum
index.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Inch</title>
</head>
<body>
<?php
if(isset($_POST['num'])){
$num=(int)$_POST['num'];
$sum=0;
for($i=1;$i<=$num;$i++){
$sum+=$i;
}
echo "<p>1から{$num}までの和は{$sum}です。</p>\n";
}else{?>
<p>和を計算します。</p>
<form method="post">
1から:<input type="number" name="num">まで<br>
<button type="submit">送信</button>
<?php } ?>
</body>
</html>

コメント