C++程序设计 基础、编程抽象与算法策略 第二章习题

#include <iostream>
using namespace std;

int roundToNearstInt(double x) {
	int y;
	if (x >= 0) {
		y = x + 0.5;
	}
	else {
		y = x - 0.5;
	}
	return y;
}
int main() {
	double x;
	cout << "Enter the number: ";
	cin >> x;
	int y = roundToNearstInt(x);
	cout << "The nearst integer is " << y << endl;
	return 0;
}
  1. 题目提示错误,而且如果要计算出无穷不循环小数需要设定小数位数
#include <iostream>
using namespace std;

double squart(int x){
	double g = x / 2.0;
	double a = x / g;
	
	while (g != a) {
		g = (x / g + g) / 2;
		a = x / g;
	}
	
	
	return g;
}
int main() {
	int x;
	cout << "Enter a number: ";
	cin >> x;
	double y = squart(x);
	cout << "The answer is " << y << endl;

	return 0;
}

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <cmath>
using namespace std;

void initRandomSeed() {
	static bool initialized = false;
	if (!initialized) {
		srand(int(time(NULL)));
		initialized = true;
	}
}
double randomReal(double low, double high) {
	initRandomSeed();
	double d = rand() / (double(RAND_MAX) + 1);
	double s = d * (high - low);
	return low + s;
}
double RandomAverage(int x) {
	double result = 0.0;
	for (int i = 0; i < x; i++) {
		double y = randomReal(0.0, 1.0);
		result += y;
	}
	double average = result / x;
	return average;
}

int main() {
	int count;
	cout << "Enter a number of count: ";
	cin >> count;

	double y = RandomAverage(count);
	cout << "The average value of random numbers is " << y << endl;
	return 0;
}

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <cmath>
using namespace std;

void initRandomSeed() {
	static bool initialized = false;
	if (!initialized) {
		srand(int(time(NULL)));
		initialized = true;
	}
}

bool coin() {
	int a = rand()%2;
	if (a == 1) {
		cout << "heads" << endl;
		return true;
	}
	else {
		cout << "tails" << endl;
		return false;
	}
}

bool threecoin(int& count) {
	for (int i = 0; i < 3; i++) {
		if (coin() == true)
			count += 1;
		else {
			count += 1;
			return false;
		}
			

	}
	return true;
}

int main(){
	initRandomSeed();
	int count = 0;
	bool a = false;
	while (!a) {
		a = threecoin(count);
	}
	cout << "It took " << count << " flips to get 3 consecutive heads." << endl;
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值