目录
数组倒序
#include <iostream>
using namespace std;
#define NUM 10
int a[NUM];
int main()
{
for(int i = 0; i < NUM; ++i)
cin >> a[i];
for(int k = NUM - 1; k >= 0; --k)
cout << a[k] << " "; //下标问题难掌握
return 0;
}
筛法求素数
#include <iostream>
using namespace std;
int main()
{
int Max_Num;
cin >> Max_Num;
bool isPrime[Max_Num+10];
for(int i = 2; i <= Max_Num; ++i)
isPrime[i] = true;
for(int k = 2; k <= Max_Num; ++k)
{
if(isPrime[k]) //检验该数是否被筛过
for(int m = 2 * k; m <= Max_Num; m = m + k) //不要用乘法,保持下标简洁
isPrime[m] = false;
}
int flag = 0;
for(int i = 2; i <= Max_Num; ++i) //i与前几次循环不同,逐一增加
{
if(isPrime[i])
{
printf("%2d ", i);
flag++;
if(flag == 5)
{
flag = 0;
printf("\n");
}
}
}
return 0;
}
数组取代分支结构
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
string weekdays[] = {"Monday", "Tuesday", "Wednesday", "Thursday"
,"Friday", "Saturday", "Sunday"};
int n;
cin >> n;
if((n > 0) && (n <= 7))
cout << weekdays[n-1];
else
cout << "Illegal";
return 0;
}
判断2012.1.22(星期天)后某天为星期几
#include <iostream>
using namespace std;
int monthdays[13] = {-1,31,28,31,30,31,30,31,31,30,31,30,31};
//巧妙绕过monthdays[0],避免被下标弄晕
int main()
{
int year, month, day;
int d = 0;
cin >> year >> month >> day;//2012.1.1(星期天)
for(int y = 2012; y < year; y++)
{
if((y % 4 == 0 && y % 100 != 0 )||(y % 400) == 0 )
d += 366;
else
d += 365;
}
if((year % 4 == 0 && year % 100 != 0 )||(year % 400) == 0 )
monthdays[2] = 29;
for(int m = 1; m < month; m++)
d += monthdays[m];
d = d + day;
d = d % 7;
cout << d - 1<< endl;
return 0;
}
矩阵乘法
#include <iostream>
using namespace std;
//开头定义好三个矩阵
#define ROWS 8
#define COLS 8
int a[ROWS][COLS];
int b[ROWS][COLS];
int c[ROWS][COLS];
int main()
{
int i, j, k;
int m, n;
cin >> m >> n;
for(i = 0; i < m; i++)
for(j = 0; j < n; j++)
cin >> a[i][j] ;
int p, q;
cin >> p >> q;
for(i = 0; i < p; i++)
for(j = 0; j < q; j++)
cin >> b[i][j];
int sum = 0;
for(i = 0; i < m; i++)
{
for(j = 0; j < q; j++)
{
for(sum = 0, k = 0; k < n; k++) //sum变量每次归0
sum += a[i][k] * b[k][j];
c[i][j] = sum;
}
} //多层,套好括号
for(i = 0; i < m; i++)
{
for(j = 0; j < q; j++)
{
cout << c[i][j] << " ";
}
cout << endl;
} //括号的使用
return 0;
}