In the process of input/C + + programs, it often determines whether or not to enter a carriage return to determine whether the program ends. In view of this application, some problems are explained. 1. Sample program 1--c language 1.1 Program source code
Enter a series of unknown numbers and then output Max, Min, and average.
#include <iostream>
#include <math.h>
#include <time.h>
using namespace std;
#pragma warning (disable:4996)
int main ()
{
int temp,n;
int max, Min, sum;
scanf ("%d", &temp);
max = min = sum = temp; Init
n = 1;
while (scanf ("%d", &temp) ==1)
{
sum = temp;
if (max <= temp) max = temp;
if (min >= temp) min = temp;
n++;
}
printf ("%d%d%.3lf\n", Max,min, (double) (sum/n));
System ("pause");
return 0;
}
The program stays in the input phase and cannot execute the result OUTPUT statement 1.2 problem Analysis
(1) The return value of scanf () is the number of input data, for example, in scanf ("%d", &temp) the normal return value is 1
(2) scanf in the detection of input due to scanf ("%d", &temp) specified the integer input, so scanf to spaces, carriage returns and tabulation symbols, etc. do not detect. After entering a carriage return on the keyboard, the program does not detect the end of the program input and remains in the while (scanf ("%d", &temp)) line. 1.3 Problem Solving
(1) Method one:
In the program window cmd enter ctrl+d (play carriage return), the program will continue to run down
(2) Method two:
Modify the code and use GetChar () to determine whether the program ends. Change the while statement in the original code to
while ((scanf ("%d", &temp) = = 1) && (GetChar ()!= ' \ n '))
#include <iostream>
#include <math.h>
#include <time.h>
using namespace std;
#pragma warning (disable:4996)
int main ()
{
int temp,n;
int max, Min, sum;
scanf ("%d", &temp);
max = min = sum = temp; Init
n = 1;
while (scanf ("%d", &temp) = = 1) && (GetChar ()!= ' \ n '))
{
sum = temp;
if (max <= temp) max = temp;
if (min >= temp) min = temp;
n++;
}
printf ("%d%d%.3lf\n", Max,min, (double) (sum/n));
System ("pause");
return 0;
}
(3) method three (not recommended):
Artificial input of error messages, such as letters or floating point numbers
2. Sample program 2--c++ language 2.1 program source code
The above example can be expressed in C + + as:
#include <iostream>
#include <math.h>
#include <time.h>
using namespace std;
#pragma warning (disable:4996)
int main ()
{
int temp, n;
int max, Min, sum;
cin>>temp;
max = min = sum = temp; Init
n = 1;
while (CIN >> temp)
{
sum = temp;
if (max <= temp) max = temp;
if (min >= temp) min = temp;
n++;
if (getchar () = = ' \ n ') break ;
cout <<max<< ' <<min<< ' << (double) sum/n<< Endl;
System ("pause");
return 0;
}