内積についてはここ。
cinで数値を入力した後、各ベクトルの数値を配列に入れて内積を計算する。
結果
1 2 3 4 5 6 7 8 9 10 11 12 13 | データ数を入力 ->3 x0->2 x1->4 x2->3 w0->1 w1->3 w2->5 2×1=2 4×3=12 3×5=15 結果 ->29 |
ソースコード。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | #include <iostream> double dot( int n, std::shared_ptr< double []> x, std::shared_ptr< double []> w) { double goukei = 0; for ( int i = 0; i < n; i++) { std::cout << x[i] << "×" << w[i] << "=" << x[i] * w[i] << std::endl; goukei = goukei + x[i] * w[i]; } std::cout << std::endl; return goukei; } int main() { std:: size_t n; while (1) { std::cout << "データ数を入力 ->" ; std::cin >> n; if ((std::cin.good() != 0) && n >= 1 && n <= 99) { break ; } std::cin.clear(); std::cin.ignore(256, '\n' ); std::cout << "もう一度数を入力 ->" ; } std::shared_ptr< double []> x( new double [n]); std::shared_ptr< double []> w( new double [n]); for (unsigned int i = 0; i < n; i++) { std::cout << "x" << i << "->" ; while (1) { std::cin >> x[i]; if ((std::cin.good() != 0) && x[i] >= 0 && x[i] < 99) { break ; } std::cin.clear(); std::cin.ignore(256, '\n' ); std::cout << "もう一度数を入力 ->" ; } } std::cout << std::endl; for (unsigned int i = 0; i < n; i++) { std::cout << "w" << i << "->" ; while (1) { std::cin >> w[i]; if ((std::cin.good() != 0) && w[i] >= 0 && w[i] < 99) { break ; } std::cin.clear(); std::cin.ignore(256, '\n' ); std::cout << "もう一度数を入力 ->" ; } } std::cout << std::endl; std::cout<< "結果 ->" << dot(n, x, w); return (0); } |
同じ動きをするnewを使った例↓
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | #include <iostream> double dot( int n, double *x, double *w) { double goukei = 0; for ( int i = 0; i < n; i++) { std::cout << x[i] << "×" << w[i] << "=" << x[i] * w[i] << std::endl; goukei = goukei + x[i] * w[i]; } std::cout << std::endl; return goukei; } int main() { unsigned int n; double * x, *w; while (1) { std::cout << "データ数を入力 ->" ; std::cin >> n; if ((std::cin.good() != 0) && n >= 1 && n <= 99) { break ; } std::cin.clear(); std::cin.ignore(256, '\n' ); std::cout << "もう一度数を入力 ->" ; } x = new double [n]; w = new double [n]; for ( int i = 0; i < n; i++) { std::cout << "x" << i << "->" ; while (1) { std::cin >> x[i]; if ((std::cin.good() != 0) && x[i] >= 0 && x[i] < 99) { break ; } std::cin.clear(); std::cin.ignore(256, '\n' ); std::cout << "もう一度数を入力 ->" ; } } for ( int i = 0; i < n; i++) { std::cout << "w" << i << "->" ; while (1) { std::cin >> w[i]; if ((std::cin.good() != 0) && w[i] >= 0 && w[i] < 99) { break ; } std::cin.clear(); std::cin.ignore(256, '\n' ); std::cout << "もう一度数を入力 ->" ; } } std::cout << std::endl; std::cout<< "結果 ->" << dot(n, x, w); delete [] x; delete [] w; return (0); } |
コメント