マルチスレッド版数独自動生成ソフトC++コードを題材とする超初心者のためのVisual Studio C++講義
第7章 関数の学習

第17話 2次元for文でコードを洗練させる!

実行結果


n = 10 3.30452
n = 100 3.16042
n = 1000 3.14356
n = 10000 3.14179
n = 100000 3.14161
n = 1000000 3.14159


を実現するコード例
#include<iostream>//インクルードファイルiostreamの読み込み

#include<conio.h>//while(!_kbhit());を使うためのお呪い

#include<string> //文字列変数を使えるようにするために組み込む

#include <iomanip> //setprecisionを使えるように組み込む

#include <cmath>//powなどを使うときに必要

#include <ctime>//time()(←現時刻発生する関数)を使うために必要

//#include<math.h>//平方根sqrt(x)を求めるために必要←#include <cmath>があるので不要でした。2026年3月3日訂正

using namespace std;//coutを使うときに必要なお呪い

double f(double n);//円周率を求める

int main() {//私は社長だ。

  double n = 1;

  for (double i = 0; i < 6; i++) {

    n = n * 10;

    double y = f(n);//円周率を求める

    cout << fixed << setprecision(0);//小数部分を表示させない←2026年3月3日修正


    cout << "n = " << n;

    for (double j = 9 - i; j >= 0; j--) {

      cout << " ";

    }

    cout << fixed << setprecision(5);//小数第5位まで表示←2026年3月3日修正

    cout << y << endl;

  }

  while (!_kbhit());//待機させるための命令

  return 0;//int main() を終わるためのお呪い

}

//円周率を求める
double f(double n) {

double x = 0;//倍精度の実数型変数を定義して0に初期化

  double d = 1 / n;

  for (double i = 0; i < n; i++) {

    x = x + d * sqrt(1 - (i * d) * (i * d));

  }

  return(4 * x);

}

第18話課題です。

社長が仕事をしすぎてきます。

部長を雇って社長の仕事を減らしましょう。

void 部長(double n);

とすることを条件とします。



第7章第16話へ 第7章第18話へ

本講義トップへ