====== 練習問題⒮ ======
練習問題(プロジェクト3個追加、mainに全部書いてもいいよ)
①入力された2つの文字列を連結して返す関数を作りなさい!
プロトタイプ宣言、定義を書いて、mainで実際に使てみて動作確認!
戻り値は? concatenate(文字列1、文字列2)
{
処理内容;
return(なにかえす?);
}
②底辺と高さを入力して、三角形の面積を返す関数
上と同じだけど、全部考えてみて!
③金額を引数にとり、金種表を出力する関数
例)denominations(1353);
10000円 札:0
5000円 札:0
1000円 札:1
500円硬貨:0
100円硬貨:3
50円硬貨:1
10円硬貨:0
5円硬貨:0
1円硬貨:3
==== ①模範解答 ====
//theMain.cpp
#include
#include
using std::string;
using std::cout;
using std::cin;
using std::endl;
// concatenate関数 引数の2つの文字列を連結して返す関数
//引数
// string str1:1個目の文字列
// string str2:2個目の文字列
//戻り値
// str1とstr2を連結した結果の文字列
string concatenate(string str1, string str2);
int main()
{
string dat1, dat2;
cout << "文字列を2つスペース区切りで入力:";
cin >> dat1 >> dat2;
string res = concatenate(dat1, dat2);
cout << dat1 << " + " << dat2 << " = " << res << endl;
return 0;
}
string concatenate(string str1, string str2)
{
return(str1 + str2);
}
==== ②模範解答 ====
//theMain.cpp
#include
using std::cout;
using std::cin;
using std::endl;
//triangleArea関数 底辺と高さから三角形の面積を返す関数
//引数
// double _base:底辺の長さ(実数)
// double _height:三角形の高さ(実数)
//戻り値
// 三角形の面積(実数)
double triangleArea(double _base, double _height);
int main()
{
double base, height;
cout << "底辺と高さをスペース区切りで入力:";
cin >> base >> height;
cout << "(底辺, 高さ)=(" << base << ", " << height << ")の三角形の面積は"
<< triangleArea(base, height) << endl;
return 0;
}
double triangleArea(double _base, double _height)
{
return(_base * _height / 2.0);
}
==== ③模範解答 ====
#include
using std::cout;
using std::cin;
using std::endl;
//denominations関数 金額を引数に金種表を表示する関数
//引数
// int _price:入力する金額(整数)
//戻り値
// なし
void denominations(int _price); //引き算でやるバージョン
void denominations_by_division(int _price);//割り算とあまりでやるバージョン
//定義
void denominations(int _price)
{
int kinds[9] = { 10000,5000,1000,500,100,50,10,5,1 };
int amount[9] = { 0, 0, 0, 0, 0, 0, 0, 0, 0 };
int i = 0;
while (_price > 0)
{
if (_price >= kinds[i])
{
_price = _price - kinds[i];
amount[i]++;
}
else
{
i++;
}
}
for (int j = 0; j < 9; j++)
{
if (j < 3)
cout << kinds[j] << "円 札:" << amount[j] << endl;
else
cout << kinds[j] << "円硬貨:" << amount[j] << endl;
}
}
void denominations_by_division(int _price)
{
int kinds[9] = { 10000,5000,1000,500,100,50,10,5,1 };
int amount[9] = { 0, 0, 0, 0, 0, 0, 0, 0, 0 };
int i = 0;
while (_price > 0)
{
if (_price >= kinds[i])
{
amount[i] = _price / kinds[i];
_price = _price % kinds[i];
}
else
{
i++;
}
}
for (int j = 0; j < 9; j++)
{
if (j < 3)
cout << kinds[j] << "円 札:" << amount[j] << endl;
else
cout << kinds[j] << "円硬貨:" << amount[j] << endl;
}
}
int main()
{
int myprice;
cout << "金額を入力:";
cin >> myprice;
denominations_by_division(myprice);
return 0;
}