#include<iostream>usingnamespace std;introundToNearstInt(double x){int y;if(x >=0){
y = x +0.5;}else{
y = x -0.5;}return y;}intmain(){double x;
cout <<"Enter the number: ";
cin >> x;int y =roundToNearstInt(x);
cout <<"The nearst integer is "<< y << endl;return0;}
题目提示错误,而且如果要计算出无穷不循环小数需要设定小数位数
#include<iostream>usingnamespace std;doublesquart(int x){double g = x /2.0;double a = x / g;while(g != a){
g =(x / g + g)/2;
a = x / g;}return g;}intmain(){int x;
cout <<"Enter a number: ";
cin >> x;double y =squart(x);
cout <<"The answer is "<< y << endl;return0;}
#include<iostream>#include<cstdlib>#include<ctime>#include<cmath>usingnamespace std;voidinitRandomSeed(){staticbool initialized =false;if(!initialized){srand(int(time(NULL)));
initialized =true;}}doublerandomReal(double low,double high){initRandomSeed();double d =rand()/(double(RAND_MAX)+1);double s = d *(high - low);return low + s;}doubleRandomAverage(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;}intmain(){int count;
cout <<"Enter a number of count: ";
cin >> count;double y =RandomAverage(count);
cout <<"The average value of random numbers is "<< y << endl;return0;}
#include<iostream>#include<cstdlib>#include<ctime>#include<cmath>usingnamespace std;voidinitRandomSeed(){staticbool initialized =false;if(!initialized){srand(int(time(NULL)));
initialized =true;}}boolcoin(){int a =rand()%2;if(a ==1){
cout <<"heads"<< endl;returntrue;}else{
cout <<"tails"<< endl;returnfalse;}}boolthreecoin(int& count){for(int i =0; i <3; i++){if(coin()==true)
count +=1;else{
count +=1;returnfalse;}}returntrue;}intmain(){initRandomSeed();int count =0;bool a =false;while(!a){
a =threecoin(count);}
cout <<"It took "<< count <<" flips to get 3 consecutive heads."<< endl;return0;}