初学c++ 有两道题不会但是有答案,请问能不能帮忙解释一下怎么做的!感谢!
1. You are given data file(data.txt) from an accelerometer that measured the acceleration of a drag racer for 7 seconds. During this time, the car, from a standing start, ran a quarter mile race. The data you are given is in meters/sec^2 and sample very millisecond. There are seven thousand data points in the file. The file consist of 700 lines of 10 data points each, text format, floating point, space delimited. After the drag racer crossed the finish line the remainder of the file is filled with -999.99. Write a program that calculates and outputs the speed of the drag racer as it crosses the finish line in units of kilometers/hour. Remember, where a is the acceleration as a function of time. You may assume that the acceleration during each millisecond interval is constant.程序代码:
#include <cstdlib> #include <iostream> #include <fstream> using namespace std; int main() { ifstream myfile; double acc[7000]; double vel = 0; int ctr = 0; myfile.open("data.txt"); for (int i = 0; i < 7000; i++) myfile >> acc[i]; myfile.close(); // integrate acc data until you hit -999.99 while (acc[ctr] != -999.99) { vel = vel + acc[ctr]*0.001; ctr++; } cout << "The velocity at the end of a quarter mile is "; cout << vel * 3600.0 / 1000.0 << " km/sec"; return 0; }
2. a. Craps is a game where a player rolls two dice. On the first roll . If the sum of the dice is 7 or 11 the wins the bet. If it is 2,3 or 12 he “craps out” and loses his money. Any other outcome and the player must roll again with further rules we won’t discuss here. Create a function called firstRoll with the following prototype:
char firstRoll( );
The function simulates the rolling of two dice and based on that returns the character ‘w’ for a win, ‘l’ for a loss, or ‘r’ for roll again. Note you must simulate the roll of each die separately and add them together. Generating a single random number between 1 and 12 will give you incorrect results.
b. Write a program that estimates the probability of winning, losing , or rolling again on the first roll of a craps game by calling firstRoll one thousand times and keeping track of the number of times each outcome occurs. The output of the program should be:
For the first craps roll
Probability of winning is 0.xx
Probability of losing is 0.yy
Probability of having to roll again is 0.zz.
程序代码:
#include <cstdlib> #include <iostream> using namespace std; char firstRoll(); int main(int argc, char** argv) { int wcnt=0,lcnt=0,rcnt=0; char outcome; for (int ctr=0;ctr<1000;++ctr){ outcome=firstRoll(); if (outcome=='w')++wcnt; if (outcome=='l')++lcnt; if (outcome=='r')++rcnt; } cout<<"For the first craps roll \n"; cout<<"The probability of winning is "<<float(wcnt)/1000<<endl; cout<<"The probability of losing is "<<float(lcnt)/1000<<endl; cout<<"The probability of having to roll again is " <<float(rcnt)/1000<<endl; return 0; }