#include <iostream>
#include <iomanip>
using namespace std;
const int N = 20;
int main ()
{
//Declare variables
int counter; //loop control variable
int number; //variable to store the new number
int zeros = 0; //Step 1
int odds = 0; //Step 1
int evens = 0; //Step 1
int positives = 0;
int negatives = 0;
// Display Program Intro telling what the program does.
cout << "********************************************************"
<< "n* This is a program that counts integers you enter as *"
<< "n* even, odd or zero and positve or negative *"
<< "n* It classifies 20 numbers or use 99999 to exit early *"
<< "n********************************************************"
<< endl;
// Ask for 20 integers with 99999 as early exit
cout << "nnPlease enter " << N << " integers, "
<< "positive, negative, or zeros."
<< "ntt or enter number 99999 to exit early. nn"
<< endl; //Step 2
cout << "The numbers you entered are:" << endl;
// Loop that classifies the numbers entered.
for (counter = 1; counter <= N; counter++) //Step 3
{
// Enter number and mirror it backed on a tabbed line.
cin >> number; //Step 3a
cout << number << endl; //Step 3b
// Early exit condition: 99999
if(number = 99999)
break; // Exit loop before 20 numbers
// Count Postive and Negative Numbers
if(number < 0)
negatives++;
else
positives++;
// Count Evens, Odds and Zeros
//Step 3c
switch (number % 2)
{
case 0:
evens++;
if (number == 0)
zeros++;
case 1:
case -1:
odds++;
} //end switch
} //end for loop
cout << endl;
// Display the results ....
//Step 4
cout << "There are " << evens << " evens, "
<< "which includes " << zeros << " zeros."
<< endl;
cout << "The number of odd numbers is: " << odds
<< endl;
cout << "The number of positive numbers is: " << positives
<< endl;
cout << "The number of negative numbers is: " << negatives
<< endl;
// Use Holdscreen to make sure the results are visible ....
char holdscr; // This character and section is to hold screen open
cout << "nntPress a character and Enter to exit program. ";
cin >> holdscr;
return 0;
}
我正在调试这个程序。程序中最初有 6 个错误。我发现了其中的四个,因为它们是语法错误。编译器没有显示任何错误,但程序也不起作用。 该程序应该存储 20 个数字,最后告诉您其中有多少是偶数、奇数、零、负数和正数。我只是C++的初学者。我已经尝试了所有可能的方法从我这边解决它,但我无法让它工作。我已经在Google上查找了所有代码和语法,为什么它以这种方式工作,但没有找到任何帮助。这里的任何帮助将不胜感激。
如果在编译时启用警告,那么编译器将帮助指出代码中的某些错误,如果心情好,它甚至可能会建议解决方案:
<stdin>:46:23: warning: using the result of an assignment as a condition without parentheses [-Wparentheses]
if(number = 99999)
~~~~~~~^~~~~~~
<stdin>:46:23: note: place parentheses around the assignment to silence this warning
if(number = 99999)
^
( )
<stdin>:46:23: note: use '==' to turn this assignment into an equality comparison
if(number = 99999)
^
始终在启用警告的情况下进行编译(例如gcc -Wall ...
( - 从长远来看,它将为您节省大量时间和调试工作。