私はこれを動作させることはできません。私は、3行3列の整数を管理するThreeBy3という名前のクラスを構築する必要があります。クラスには配列を表示し、配列がマジックスクエアの基準に適合するかどうかを判断するメソッドが必要です。
以下のファイルから3 x 3配列を読み取ります。読み取られるたびに、ThreeBy3のインスタンスを作成し、配列を表示し、それに続いて配列が魔方陣であるかどうかを示す出力行を続けます。不要になったインスタンスを削除することを忘れないでください。2次元配列マジックスクエア
最後にダイナミックポインタに問題があります。これは私が持っているコードであるあなたに
ありがとう:
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <istream>
using namespace std;
using std::cout;
using std::endl;
using std::istream;
{
class ThreeBy3
{
static const int SQ = 3;
static const int rows[][3][2];
static const int rowCount;
int square[SQ][SQ];
int sum;
public:
ThreeBy3(int ms[][3]);
bool isMagicSquare();
void display(std::ostream& os);
};
const int ThreeBy3::rows[][3][2] = {
{ { 0, 0 }, { 0, 1 }, { 0, 2 } },
{ { 1, 0 }, { 1, 1 }, { 1, 2 } },
{ { 2, 0 }, { 2, 1 }, { 2, 2 } },
{ { 0, 0 }, { 1, 0 }, { 2, 0 } },
{ { 0, 1 }, { 1, 1 }, { 2, 1 } },
{ { 0, 2 }, { 1, 2 }, { 2, 2 } },
{ { 0, 0 }, { 1, 1 }, { 2, 2 } },
{ { 0, 2 }, { 1, 1 }, { 2, 0 } },
};
const int ThreeBy3::rowCount = (sizeof rows)/(sizeof rows[0]);
bool ThreeBy3::isMagicSquare()
{
for (int i = 0; i < 8; i++)
{
int x = 0;
for (int j = 0; j < 3; j++)
x += square[rows[i][j][0]][rows[i][j][1]];
if (x != sum)
return false;
}
return true;
}
void ThreeBy3::display(std::ostream& os)
{
const int W = 2;
os << std::setprecision(1) << std::fixed;
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
cout << square[i][j] << " ";
cout<< endl;
}
}
}
int main()
{
static const int SQ = 3;
std::ifstream ifs;
std::string path = "path-to/msq2.txt";
int iv;
int ix, jx;
int ms[3][3] = { { 0 }, { 0 }, { 0 } };
int rcd = 0;
ThreeBy3 *msq;
ifs.open(path);
if (!ifs)
{
cout << "file not found:" << path << endl;
return -1;
}
while (!ifs.eof())
{
bool readThreeBy3(std::istream& strm, int ms[][3]);
{
int ix, jx, iv;
for (ix = 0; ix < 3; ++ix)
{
for (jx = 0; jx < 3; ++jx)
{
strm >> iv;
if (strm.eof())
return false;
ms[ix][jx] = iv;
}
}
return true;
}
++rcd;
if (msq->isMagicSquare())
{
cout << " is a magic square" << endl;
}
else
{
cout << " is NOT a magic square" << endl;
}
}
eof:
ifs.close();
return 0;
}
これは、ファイル
2 7 6
9 5 1
4 3 8
2 9 4
7 1 3
6 5 8
4 3 8
9 5 1
2 7 6
4 9 2
3 7 5
8 1 6
6 1 8
7 5 3
2 9 4
6 7 2
1 5 9
8 3 4
8 1 6
3 5 7
4 9 2
8 3 4
1 6 9
5 7 2
これは有効なコードではありません - それはコンパイルされません。例えば、関数readThreeBy3は別の関数の中にあります...最後に動的ポインタを使用していた場合、どんな種類のポインタを使用しているかを言った方が便利です。 –
私はそれをコンパイルする方法を知りませんが問題です。私はその機能をどこに置くべきかわかりません。また、動的ポインタ* msgの場合、なぜそれが認識されないのか、どのように宣言しなければならないのか分かりません –