【问题标题】:An access violation (segmentation fault) raised in my program?我的程序中出现访问冲突(分段错误)?
【发布时间】:2013-04-28 21:37:43
【问题描述】:

这个程序让我非常头疼。无论出于何种原因,它一旦到达“学生 3”就会崩溃。我找不到任何它陷入的无限循环或任何其他导致它在那时崩溃的原因。非常感谢任何帮助。

#include <iostream>
#include <string>
using namespace std;

int main()
{
 const int ARRAY_SIZE = 5;
 const int ARRAY_SIZE_TWO = 4;
 const int ARRAY_SIZE_THREE = 20;
 string names[ARRAY_SIZE];
 double grades[ARRAY_SIZE];
 double average[ARRAY_SIZE];
 double averageFinal[ARRAY_SIZE];
 string letter[ARRAY_SIZE] = {"A", "B", "C", "D", "F"};
 string studentLetter[ARRAY_SIZE]; 
 int counterOne = 0;
 int counterTwo = 0;
 int counterThree = 0;
 double temp;
 while (counterOne < ARRAY_SIZE)
 {
  system("CLS");
  cout<<"Enter the name of student number " <<(counterOne + 1) <<":"<<endl;
  cin>>names[counterOne];
  while(counterTwo < ARRAY_SIZE_TWO)
  {
   system("CLS");
   cout<<"Enter the test scores for " <<names[counterOne] <<":" <<endl;
   cout<<"Enter test score number " <<(counterTwo + 1) <<" for " <<names[counterOne] <<":" <<endl;
   cin>>grades[counterThree];
   counterTwo += 1;
   counterThree += 1;
   average[counterOne] += grades[counterThree];
  }
  counterTwo = 0;
  counterOne += 1;
 }
 counterOne = 0;
 counterTwo = 0;
 counterThree = 0;
 while(counterOne < ARRAY_SIZE)
 {
  averageFinal[counterOne] = average[counterOne] / 12;
  if (averageFinal[counterOne] < 89)
  {
   studentLetter[counterOne] = letter[0];
  }
  else if (averageFinal[counterOne] < 79)
  {
   studentLetter[counterOne] = letter[1];
  }
  else if (averageFinal[counterOne] < 69)
  {
   studentLetter[counterOne] = letter[2];
  }
  else if (averageFinal[counterOne] < 59)
  {
   studentLetter[counterOne] = letter[3];
  }
  else
  {
   studentLetter[counterOne] = letter[4];
  }
  counterOne += 1;
 }

 while(counterTwo < ARRAY_SIZE)
 {
  cout<<names[counterTwo] <<":" <<endl <<"Average: " <<averageFinal <<"%" <<endl <<"Letter Grade: " <<studentLetter[counterTwo] <<endl;
  counterTwo += 1;
 }
 system("PAUSE");
 return 0;
}

【问题讨论】:

  • 你能追踪到导致问题的代码行吗?这将有助于我们帮助您。
  • 不相关,但第一个 if 语句对于
  • 老实说,我不确定如何跟踪导致问题的代码行。我还是 C++ 的新手。有什么办法可以逐行运行程序吗?
  • 你为什么不重置CounterThree
  • counterThree 稍后用于计算平均值,在我通过输入阶段之前,我无法测试如何进行平均值计算。

标签: c++ if-statement crash while-loop counter


【解决方案1】:

正如 vidit 所指出的,counterThree 允许在读取循环中溢出 ARRAY_SIZE。您需要重新设置它,或稍后使用不同的计数器。一个好的做法是尽可能缩小变量的范围,而不是重复使用变量(避免“临时”),这可能会导致簿记混乱。

【讨论】:

    猜你喜欢
    • 2011-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-05
    • 1970-01-01
    • 2012-11-01
    • 1970-01-01
    相关资源
    最近更新 更多