输入1得九九乘法表,输入2得水仙花数,输入3得斐波拉契数列,输入4得奇阶幻方,的c++代码编程
时间: 2024-01-15 22:19:11 浏览: 60
2017JAVA算法经典编程题全集(50题及答案)
以下是根据您的需求编写的C++代码示例:
1. 输入1得九九乘法表:
```cpp
#include <iostream>
using namespace std;
int main() {
for (int i = 1; i <= 9; i++) {
for (int j = 1; j <= i; j++) {
cout << j << " * " << i << " = " << i * j << "\t";
}
cout << endl;
}
return 0;
}
```
2. 输入2得水仙花数:
```cpp
#include <iostream>
using namespace std;
int main() {
for (int i = 100; i <= 999; i++) {
int j = i;
int sum = 0;
while (j) {
int k = j % 10;
sum += k * k * k;
j /= 10;
}
if (sum == i) {
cout << i << " ";
}
}
return 0;
}
```
3. 输入3得斐波那契数列:
```cpp
#include <iostream>
using namespace std;
int main() {
int n;
cout << "请输入斐波那契数列的长度:";
cin >> n;
int first = 0, second = 1;
cout << "斐波那契数列前 " << n << " 项为:";
for (int i = 0; i < n; i++) {
cout << first << " ";
int temp = first;
first = second;
second = temp + second;
}
return 0;
}
```
4. 输入4得奇阶幻方:
```cpp
#include <iostream>
using namespace std;
int main() {
int n;
cout << "请输入奇数阶幻方的阶数:";
cin >> n;
if (n % 2 == 0) {
cout << "输入错误,阶数必须为奇数!";
return 0;
}
int magicSquare[n][n];
memset(magicSquare, 0, sizeof(magicSquare));
int row = 0;
int col = n / 2;
for (int num = 1; num <= n * n; num++) {
magicSquare[row][col] = num;
row--;
col++;
if (row < 0) {
row = n - 1;
}
if (col == n) {
col = 0;
}
if (magicSquare[row][col] != 0) {
row++;
col--;
if (row == n) {
row = 0;
}
if (col < 0) {
col = n - 1;
}
row++;
}
}
cout << "奇阶幻方为:" << endl;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cout << magicSquare[i][j] << "\t";
}
cout << endl;
}
return 0;
}
```
阅读全文