c++当循环在填充数组时没有正确终止时,希望能帮助退出此循环

c++ While loop not terminating properly when filling an array, would like help exiting this loop

本文关键字:循环 希望 终止 帮助 退出 填充 数组 c++      更新时间:2023-10-16

我目前正在尝试用一个带有终止条件(输入>0)的while循环填充一个双数组。数组正在填充,循环似乎正在工作,但是当输入-1时,程序似乎不会退出循环。我已经试着用cout语句调试这个问题好几个小时了,我真的很感激任何帮助。

double calc(double a[],double dev[], int n,double *mean);
void letter(double a[],char letg[],double std,double *mean);
int main(void)
{double a[6],dev[6],mean, std;
int i,n;
int entered;
char letg[6];
cout<<"Please enter the test grades one at a time (max 6)n";
cout<<"enter a -1 when you are done entering scoresn";
//based off class notes
i=0;
cin>>entered; 
while (entered>0 && i<=6)
{a[i]=entered;
i++; 
cin>>entered;
}
i=n
cout<<"out of loop";
std=calc(a,dev,n,&mean);
letter(a,letg,std,&mean);
cout<<"the corresponding scores and letter grades are:n";
 cout<<a;
cout<<letg;
return 0;
}
double calc(double a[],double dev[],int n,double *mean)
{int c,i;
cout<<"in calc";
double sum,sqdif,std;
c=0;
sum=0;
while (c<=n)
{sum=sum+a[c];
c++;
}
*mean=sum/(n+1);
for (i=0;i<=n;i++)
dev[n]=pow((a[n]-*mean),2);
for(i=0;i<=n;i++)
sqdif=dev[i]+sqdif;
std=sqrt(sqdif/c);
return std;
}

问题可能是负数(大小问题)。尝试另一个正数退出,例如99也尝试使用出口控制循环的相同代码,即do..while

您给出的输入序列是什么。当我尝试时,它退出了循环

在解决了i<6的问题(而不是像Borglider指出的那样导致segfault的i<=6)后,纠正这个问题:

double entered;   // should be double and not int 

使用在int int处声明的entered,如果您输入一个浮点数字,例如0.5,它将停止在点处读取(因为点对整数无效),并且永远无法读取您将键入的所有其他数字。

建议:检查有效输入可能是一种很好的做法,例如将cin>entered;替换为:

    // cin>>entered; => if wrong input, you'll not do anything about it
    while (!(cin >> test) && cin.fail() && ! cin.eof()) {  // check if  input failed, and for another reason that an eof. 
        cout << "Wrong input. Enter again ! ";
        cin.clear();    // reset error flag
        cin.ignore(SIZE_MAX, 'n');  // discard faulty input
    }

也许可以远离数组,转而使用向量:

int main(void)
{
    std::vector<double> scoreList; 
    double score;
    // Intro msg
    std::cout << "Please enter the test grades one at a time (max 6)" << std::endl;
    std::cout << "enter a -1 when you are done entering scores" << std::endl;
    // Loop for up to 6 scores, exit loop when 6 entered.
    while (scoreList.size() < 6)
    {
        std::cin >> score;
        // Exit loop if -1 entered
        if (score == -1.0)
            break;
        scoreList.push_back(score);
    }
    // Access scores and display
    for (std::vector<double>::iterator v = scoreList.begin(); v != scoreList.end(); v++)
        std::cout << "Score entered: " << *v << std::endl;
    return 0;
}

结果是没有缓冲区溢出,所需要的只是遍历输入的数字列表。

在分配变量之前,必须初始化变量。

i=n      //n = ?

sqdif=dev[i]+sqdif;       //sqdif = ?

考虑这个关于未初始化变量错误的例子-

int main() {
   int i;
   return i;   // C4700
}