C++ 関数と配列オブジェクト

関数と配列オブジェクト

序文

衝動的な人は、「何を学べばよいでしょうか?」と尋ねる傾向があります。聞かずに、ただ学んでください。

C++ では、クラス オブジェクトは構造に基づいているため、構造プログラミングにおける考慮事項の一部はクラスにも当てはまります。

配列形式

array<データ型、要素数> 配列名 = {配列要素};

1. 例

この例では、配列オブジェクトを使用して、1 年の 4 四半期分の経費を保存します。コードは次のとおりです。

#include<iostream>
#include<string>
#include<array>
using namespace std;
const int Seasons = 4;
const array<string, Seasons>Snames = {
    
    "Spring","Summer","Fall","Winter"};//定义一个array类型
void fill(array<double, Seasons>* pa);
void show(array<double, Seasons>da);
int main()
{
    
    
	array<double, Seasons>expenses;
	fill(&expenses);
	show(expenses);
	return 0;
}
void fill(array<double, Seasons>* pa)
{
    
    
	for (int i = 0; i < Seasons; i++)
	{
    
    
		cout << "Enter " << Snames[i] << " expenses:";
		cin >> (*pa)[i];
	}
}
void show(array<double, Seasons>da)
{
    
    
	double total=0.0;
	cout << "Expenses:" << endl;
	for (int i = 0; i < Seasons; i++)
	{
    
    
		cout << Snames[i] << ":" << da[i] << endl;
		total+= da[i];
	}
	cout << "Total expenses:" << total << endl;
}	

おすすめ

転載: blog.csdn.net/weixin_68153081/article/details/126452298