C++结构,函数不能打印最小直径

C++ struct, function can't print smallest diameter

本文关键字:打印 不能 结构 函数 C++      更新时间:2023-10-16

这是我的代码,到目前为止,我遇到的问题是打印出行星的最小直径。更新代码。。。。仍然不起作用。。。

 #include <iostream>
 #include <string>
 using namespace std;
struct Planet
{
  string name;
  int distanceSun;
  int diameter;
  int mass;
};
int PrintPlanet(Planet  planet)
{
   cout << "Name: " << planet.name << endl;
   cout << "Distance to the sun: " << planet.distanceSun << endl;
   cout << "Diameter: " << planet.diameter << endl;
   cout << "Mass: " << planet.mass << endl;
   return 0;
}
int FindSmallestDiameter(Planet * arr, int n)
{   
   int resultSmallest = INT_MAX;
   for (int j = 1; j < n; j++)
   {
       if(arr[j].diameter < arr[resultSmallest].diameter)
       {
           resultSmallest = j;
       }
   }
   return resultSmallest;
}       
int main()
{
   struct Planet * planet;
   int numberPlanet;
   cout << "Enter a value for planets: ";
   cin >> numberPlanet;
   planet = new Planet[numberPlanet];   
   int enterSelection;
  do
  {
     cout << "Enter selection: n" <<
         "1. Print the planet with the smallest diametern" << 
         "0. Exit progrman";
     cin >> enterSelection;
     switch(enterSelection)
     {
        case 1:
        {
           int heaviest = FindHeaviestPlanet(planet, numberPlanet);
           if (heaviest < 0)
           {
              cout << "No planet defined.n";
           }
           else
           {
              cout << "Heaviest planet: n";
              PrintPlanet(planet[heaviest]);
           }
       }
       break;
   } 

'当在菜单中使用较小直径控制台打印在行星上设置打印命令时:姓名:到太阳的距离:0直径:0质量:0

无论main()中缺少代码、语法错误以及填充行星的方式如何,您的搜索函数FindSmallestDiameter()都将永远无法工作:

  • resultSmallest = INT_MAX开始。这是一个非常非常大的数字
  • 然后用j=1开始循环(通常数组索引从0开始)
  • 然后尝试访问arr[resultSmallest].diameter,这是越界的,并导致未定义的行为。它可能会造成严重破坏或分割错误,但也可能返回随机数,甚至0
  • 请注意,即使行星阵列为空,此函数也不会返回负数。因此,你的信息"没有定义的行星"将永远不会显示。更糟糕的是,如果没有定义行星,您将返回INT_MAX,这可能会导致main()中的代码(试图)访问更多越界的元素

可能的修正:

int FindSmallestDiameter(Planet * arr, int n)
{   
   if (n==0) 
       return -1;    // handle special case first
   else {  
       int resultSmallest = 0;  // let's suppose the smallest is the first element
       for (int j = 1; j < n; j++) { // then it makes sense to loop starting with the second
          if(arr[j].diameter < arr[resultSmallest].diameter) // and challenge the current smalest
              resultSmallest = j;
       }
       return resultSmallest; 
    } 
}

或者使用标准算法std::min_element():的较短算法

int FindSmallestDiameter(Planet * arr, int n)
{   
   return n==0 ? -1 : std::min_element(arr,arr+n,[](const Planet &a,const Planet &b)->bool {return a.diameter<b.diameter;})-arr;
}   

问题通过以下函数解决:

 Planet FindSmallestDiameter(Planet * arr, int n)
 {
    Planet smallestDiameter = arr[0];
    for (int i = 0; i < n; i++)
    {
       if (smallestDiameter.diameter < arr[i].diameter)
       {
          smallestDiameter = arr[i];
       }
    }
    return smallestDiameter;
 }