【发布时间】:2015-06-12 14:39:09
【问题描述】:
我有一个 C 程序。我计算了数组每一行的总和,然后将它们进行比较以找出哪一行是最小总和,哪一行是最大总和。但是我的程序有时会给出正确的输出,但有时会出错。问题出在哪里?请帮我。谢谢
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
///////Prototypes of functions
void displayMaxMinElement(int array[10][10]);
void fillBoard(int array[10][10]);
void rowSum(int array[10][10]);
void displayBoard(int array[10][10]);
/////Starting main function
main() {
int board[10][10] = {0};
system("cls"); ///To clear previous data on screen
fillBoard(board);
displayBoard(board);
displayMaxMinElement(board);
rowSum(board);
system("pause>nul"); ///Pausing the program without printing "Press any key to continue"
}
void displayMaxMinElement(int array[10][10]) {
int max = 0, min = 100;
for(int i=0;i<10;i++) {
for(int j=0; j<10; j++) {
if(array[i][j] <= min)
min = array[i][j];
if(array[i][j] >= max)
max = array[i][j];
}
}
cout<<"\n\nArray element with maximum value: "<<max<<endl;
cout<<"Array element with minimum value: "<<min<<endl<<endl;
}
void fillBoard(int array[10][10]) {
srand(time(0));
for(int i = 0; i < 10; i++) {
for(int j = 0; j < 10; j++) {
array[i][j] = rand()%100+1;
}
}
}
void rowSum(int array[10][10])
{
int maxRow=0, minRow=10000;
int minRowNo, maxRowNo;
int sum[10]={0};
for(int i=0; i<10; i++)
for(int j=0; j<10; j++) {
sum[i]=sum[i]+array[i][j];
/// cout<<endl<<sum[i]<<"="<<sum[i]<<"+"<<array[i][j];
}
for(int i=0; i<10; i++)
{
if(sum[i]<=minRow){
minRow=sum[i];
minRowNo=i;
}
else if(sum[i]>=maxRow){
maxRow=sum[i];
maxRowNo=i;
}
/// cout<<endl<<"*********"<<sum[i];
}
cout<<endl<<"Row"<<minRowNo<<"is minimum and having sum of"<<minRow;
cout<<endl<<"Row"<<maxRowNo<<"is maximum and having sum of "<<maxRow;
}
void displayBoard(int array[10][10]){
int *ptr = *array;
for(int i = 1; i <= 100; i++) {
cout<<*ptr<<"\t";
ptr++;
if(i%10 == 0)
cout<<endl;
}
cout<<endl;
ptr = NULL;
}
【问题讨论】:
-
它正在运行,但有一些逻辑或隐藏错误
-
这明明是C++,不是C,应该是
int main() -
else if在rowSum()中是否正确? -
@SouravGhosh
else if有什么问题? -
你应该提供你的程序给出错误输出的输入。