//测试这个程序的运行结果为 7 28
#include <iostream>
using namespace std;
int main() {
int x = 2, y = 0, z;
x += 3 + 2; printf("%d", x);
x *= y = z = 4; printf("%d", x);
}
//三元运算符的一个典型例子
#include <iostream>
using namespace std;
int main() {
int x = 0;
cout << (x <= 0 ? (x == 0 ? 0 : 1 ): -1) << endl;
cout << (x <= 0 ? x == 0 ? 0 : 1 : -1) << endl << endl;
x = -100;
cout << (x <= 0 ? (x == 0 ? 0 : 1 ): -1) << endl;
cout << (x <= 0 ? x == 0 ? 0 : 1 : -1) << endl << endl;
x = 100;
cout << (x <= 0 ? (x == 0 ? 0 : 1 ): -1) << endl;
cout << (x <= 0 ? x == 0 ? 0 : 1 : -1) << endl << endl;
}
//据说是用泰勒级数求出自然常数(欧拉常数)e的近似值
// e = 1 + 1/1! + 1/2! + 1/3! + ...
#include <stdio.h>
#define EPS 1e-8
int main(void) {
double e = 0, fact = 1;
long n = 0;
do {
n++;
fact *= n;
e += 1 / fact;
} while (1 / fact >= EPS);
e++;
printf("e = %0.8f\n", e);
return 0;
}
//挑出每一位的阶乘之和等于该数的数, 这个没法演算似乎有问题。
#include <iostream>
using namespace std;
unsigned int fact(unsigned int n) {
unsigned int fact = 1;
unsigned int i = 1;
if(!n) {
return 0;
}
while(i <= n) {
fact *= i;
i++;
}
return fact;
}
unsigned int _fact(unsigned int n) {
switch(n) {
case 0:
return 0;
case 1:
return 1;
case 2:
return 2;
case 3:
return 6;
case 4:
return 24;
case 5:
return 120;
case 6:
return 720;
case 7:
return 5040;
case 8:
return 40320;
case 9:
return 362880;
default:
return 0;
}
}
unsigned int sumoffact(unsigned int n) {
unsigned int sum = 0;
unsigned int a[0xff], i = 0, j = 0;
while(n) {
a[i++] = n % 10;
n /= 10;
}
while(j < i) {
sum += _fact(a[j++]);
}
return sum;
}
int main() {
for(int i = 0; i < 10; i++) {
cout << fact(i) << endl;
}
for(int i = 1; i < 20000000; i++) {
if(i == sumoffact(i)) {
cout << i << " ";
}
}
}
//挑出即是回文又是素数的数
#include <iostream>
using namespace std;
int is_prime(unsigned int n) {
for(int i = 2; i < n; i++) {
if(!(n % i)) {
return 0;
}
}
return 1;
}
unsigned int _strlen(char* s) {
unsigned int len = 0;
while(*s++) {
len++;
}
return len;
}
int is_palindrome(unsigned int n) {
char s[0xff], *sp = s;
unsigned int len;
while(n) {
*sp++ = n % 10 + '0';
n /= 10;
}
*sp = '\0';
len = _strlen(s);
for(int i = 0, j = len - 1; (i < len / 2) && (j >= len / 2); i++ , j--) {
if(s[i] != s[j]) {
return 0;
}
}
return 1;
}
int main() {
for(int i = 1; i < 100000000; i++) {
if(is_palindrome(i) && is_prime(i)) {
printf("%d ", i);
}
}
}
//字符串中挑出数字并反向输出
#include <iostream>
using namespace std;
unsigned int _strlen(const char* s) {
unsigned int len = 0;
while(*s++) {
len++;
}
return len;
}
int main() {
char s[0xff], *sp = s, st[0xff], *stp = st, _st[0xff];
cin >> s;
while(*sp) {
if(*sp >= '0' && *sp <= '9') {
*stp++ = *sp++;
} else {
sp++;
}
}
*stp = '\0';
stp = st;
for(stp += _strlen(st) - 1, sp = _st; stp >= st; stp--, sp++) {
*sp = *stp;
}
*sp = '\0';
cout << st << endl;
cout << _st << endl;
}