이 코드는 수집 된 달걀 수를 취하여 사용자가 음수를 입력 할 때까지 수십과 여분의 수를 출력하는 루프를 세 번 실행하는 데 사용됩니다. 그런 다음 수집 된 (입력 된) 평균 알의 양을 인쇄하고 총 수십 개와 여분을 출력합니다. 우리가 사용하는 할당 된C++ : 조건에 따라 루프를 끝내는 데 문제가 있습니까?
의 입력은 : -1 -999, -5.
-5를 입력 할 때까지 모든 것이 정상입니다. 선생님은 인쇄 할 수십개와 엑스트라의 평균 수 또는 총 수를 원하지 않습니다.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int eggNum;
int eggDozens;
int eggExtra;
int eggTotal;
int loopCount;
int forCount;
float eggAvg;
int totalDozens;
int totalExtra;
for(forCount = 1; forCount <= 3; forCount=forCount + 1)
{
cout << left << "TEST #" << forCount << ":" << endl;
cout << "Welcome to Aunt Ellen\'s eggs to dozens converter!";
cout << endl << endl;
cout << "\tEnter the number of eggs gathered: ";
cin >> eggNum;
eggTotal = 0;
loopCount = 0;
while(eggNum >= 0)
{
eggDozens = eggNum/12;
eggExtra = eggNum % 12;
if(eggDozens != 0)
{
if(eggExtra != 0)
{
cout << "\tYou have " << eggDozens << " dozen ";
cout << eggExtra << " eggs.";
cout << endl << endl;
}
else
{
cout << "\tYou have " << eggDozens << " dozen eggs.";
cout << endl << endl;
}
}
else
{
cout << "\tYou have " << eggExtra << " eggs.";
cout << endl << endl;
}
loopCount = loopCount + 1;
eggTotal = eggTotal + eggNum;
cout << "\tEnter the number of eggs gathered: ";
cin >> eggNum;
}
cout << endl << "TOTALS:" << endl;
eggAvg = eggTotal/float(loopCount);
cout << "\tOn average " << eggAvg << " eggs have been";
cout << " gathered.";
totalDozens = eggTotal/12;
totalExtra = eggTotal % 12;
cout << endl << "\tA total of " << totalDozens << " dozen ";
cout << totalExtra << " and eggs have been gathered!" << endl;
cout << endl << endl;
}
return 0;
}
그리고 출력 :
이TEST #1:
Welcome to Aunt Ellen's eggs to dozens converter!
Enter the number of eggs gathered: 43
You have 3 dozen 7 eggs.
Enter the number of eggs gathered: 31
You have 2 dozen 7 eggs.
Enter the number of eggs gathered: -1
TOTALS:
On average 37 eggs have been gathered.
A total of 6 dozen 2 and eggs have been gathered!
TEST #2:
Welcome to Aunt Ellen's eggs to dozens converter!
Enter the number of eggs gathered: 24
You have 2 dozen eggs.
Enter the number of eggs gathered: 8
You have 8 eggs.
Enter the number of eggs gathered: 14
You have 1 dozen 2 eggs.
Enter the number of eggs gathered: -999
TOTALS:
On average 15.3333 eggs have been gathered.
A total of 3 dozen 10 and eggs have been gathered!
TEST #3:
Welcome to Aunt Ellen's eggs to dozens converter!
Enter the number of eggs gathered: -5
TOTALS:
On average -1.#IND eggs have been gathered.
A total of 0 dozen 0 and eggs have been gathered!
내가 맨 마지막 "TOTALS"와 선이 다음 싶지 않아 다음과 같이
소스 코드입니다. -5를 입력 한 후 프로그램을 종료하고 싶습니다.
@ merlin2011 입력 한 숫자가 0보다 작 으면 루프가 끝나는 조건을 설정합니다. – user3517567
그러나 '-1' 입력 후에도 프로그램이 종료되지 않습니다.마지막 TOTALS 블록을 차단하려고합니까? – merlin2011
@ merlin2011 음수를 입력하면 WHILE-LOOP가 종료됩니다. 그러나 중첩 된 for 루프는 중괄호 안의 내용을 세 번 실행합니다. 그리고 네. 아마도 평균이 0보다 작 으면 총계를 인쇄하지 말라는 if 문을 수행 할 수 있습니다. – user3517567