Logical error
May 2, 2020 at 9:17pm UTC
My question is whether anyone can tell me what the flaw is in my while () control structure loop that is causing the number of dishes to be incorrect.
It takes a minutes to prepare the first dish, and each following dish takes b minutes longer than the previous dish. She has t minutes to prepare the dishes.
For example, if the first dish takes a = 10 minutes and b = 5, then the second dish will take 15 minutes, the third dish will take 20 minutes, and so on.
If she has 80 minutes to prepare the dishes, then she can prepare four dishes because 10 + 15 + 20 + 25 = 70.
A data file has been provided with the following data, where a, b, and t are described above.
a b t
inputFile
10 5 70
5 15 85
12 9 75
10 6 60
20 10 100
15 8 95
4 3 35
20 10 200
9 5 65
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
#include<iostream>
#include<fstream>
#include <string>
#include <iomanip>
#include<conio.h>
using namespace std;
int main()
{
string inputFileName; // Declarations
string outputFileName;
ifstream inputFile;
ofstream outputFile;
int a = 0;
int b = 0;
int t = 0;
int timeTakenSoFar = a;
int timeToCompleteThisDish = a;
int numberOfDishes = 0;
// open up the resources
inputFile.open("times.txt" );
//check if the file sucessfully opened
if (!inputFile.is_open()) {
cout << "Error. \n file would not open " << endl;
exit(1);
}
// This section echos the input
while (inputFile.peek() != EOF) {
inputFile >> a >> b >> t;
cout << left << setw(3) << a
<< setw(6) << b << setw(9) << t << "\n" << endl;
}
cout << "end of file\n" << endl;
// clear
inputFile.clear();
// restart
inputFile.seekg(0);
// open up the resources
outputFile.open("Preptime.txt" );
// non-looped output section
outputFile << setw(10) << "Variable A" << setw(22) << "Variable B "
<< setw(33) << "Variable t" << setw(40) << "Number of Dishes" << endl;
//priming statment
//inputFile >> a >> b >> t;
//begin loop
while (inputFile.good()){
// ok we havn't made anything yet
timeTakenSoFar = 0;
numberOfDishes = 0;
timeToCompleteThisDish = a;
while (timeTakenSoFar + timeToCompleteThisDish <= t) {
numberOfDishes = numberOfDishes + 1;
// but the next one takes longer
timeTakenSoFar = timeTakenSoFar + timeToCompleteThisDish;
timeToCompleteThisDish = timeTakenSoFar + b;
}
//output to the new file
inputFile >> a >> b >> t;
outputFile << setw(5) << a;
outputFile << setw(26) << b;
outputFile << setw(36) << t;
outputFile << setw(37) << numberOfDishes << endl;
}
return 0;
}
May 2, 2020 at 9:55pm UTC
This:
timeToCompleteThisDish = timeTakenSoFar + b;
should be:
timeToCompleteThisDish = timeToCompleteThisDish + b;
which can also be written (the preferred way) :
timeToCompleteThisDish += b;
Topic archived. No new replies allowed.