例3-5
设计思路:
1.输入两个数。
2.比较他们平方的大小。
3.如果第一个数大执行第一个步骤,否则执行第二个。
流程图:
代码实现:
#include<iostream> #include<cmath> using namespace std; double sin(double x) { double e = 1e-10; double a = x; double sum = 0; int b=1; do { sum += a; b++; a = -a * x * x / (2 * b - 1) / (2 * b - 2); } while (fabs(a) >= e); return sum; } int main() { double r, s; double a; cin >> r >> s; if ((r * r) > (s * s)) { a = sin(r * s) / 2; } else { a = sqrt(sin(r) * sin(r) + sin(s) * sin(s)); } cout << a; return 0; }
例3-6
投骰子的随机游戏
设计思路:
1.输入一个数x。
2。以该数为种子求出两个数的和。
和为7或11宣布胜利,和为2、3或12宣告失败,以此值继续上面进程,知道胜利或失败。
流程图:
代码实现:
#include<iostream> using namespace std; int rollDice() { int a = 1 + rand() % 6; int b = 1 + rand() % 6; cout << "player rolled" << a << "+" << b << "=" << a + b << endl; return a + b; } int main() { int x; cin >> x; srand(x); int sum = rollDice(); if (sum == 7 || sum == 11) { cout << "胜利" << endl; } else if (sum == 2 || sum == 3 || sum == 12) { cout << "失败" << endl; } while (sum != 2 && sum != 3 && sum != 7 && sum != 11 && sum != 12) { sum = rollDice(); x = sum; srand(x); if (sum == 7 || sum == 11) { cout << "胜利" << endl; } else if (sum == 2 || sum == 3 || sum == 12) { cout << "失败" << endl; } } return 0; }
标签:include,第三章,cout,int,double,sum,例题,部分,sin From: https://www.cnblogs.com/xuechenhao173/p/17324026.html