Writer a Program that tests Benford\'s Law. Collect a list of at least 100 numbe
ID: 441274 • Letter: W
Question
Writer a Program that tests Benford's Law. Collect a list of at least 100 numbers from some real-life data source and enter them inter a text file. Your program should loop through the list of numbers and count how many times 1 is the first digit, 2 is the first digit, etc. For each digit output the perent it appears as the first digit. If you read a number into the string variable named strNum then you can access the first digit as a char by using strNum[0]. This is described in more detail in chapter 9 summary of bugs: Nothing is getting encoded to numtimes. Strnum[0] is not locating the first digit of a number. #include #include #include using namespace std; int main () { fstream inputStream; inputStream.open("100list.txt"); string Strnum; int numtimes[9] = { 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0} ; int total = 0; int i = 0; double percent; while(inputStream >> Strnum) { //go through every character in file. cout << Strnum[0] << endl; // not outputting the right numbers! ; //converting first char to int while (Strnum[0] != i) //compares Strnum[0] to i until we find { ++i; cout << i << endl; } // this section isn't working. nothing in numtimes gets incoded numtimes[i]++; // increases the count for a given i. if strnum[0] = 9 then numtimes[9] would be incremented total++; // evertime we find a match we increment the total; i = 0; //reset i back to 0 } for (i = 0; i< 9; ++i) { cout << numtimes[i] << endl; } // since encoding isn't working I can't tell if this is working! calculate percentages here // for (i = 1; i < 10; ++i); { percent = ((numtimes[i]/ total) *100); cout << i <<" appeared " << percent << " percent of the time" << endl; } system("pause"); inputStream.close(); return 0; }Explanation / Answer
Take the input from a file. Store the value in a string array. Now simply check the first index of the arrays and see which number it is. Correspondingly, increment a counter for that number. In this way, you will get to know the frequency of the digits as the 1st character of all the given numbers. Cheers! Please rate :)
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.