Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/162.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++;For to While循环 我想知道是否可以用< C++ > 来改变 > 循环> 循环。_C++ - Fatal编程技术网

C++;For to While循环 我想知道是否可以用< C++ > 来改变 > 循环> 循环。

C++;For to While循环 我想知道是否可以用< C++ > 来改变 > 循环> 循环。,c++,C++,下面是部分代码 int sum = 0; for (int i = 0; i < length; i++) { sum = sum + MyList[i]; } cout << "The Total is: " << sum <<endl; int largest = MyList[0]; for (int i = 0; i < length; i++) if ( MyList[i] > largest )

下面是部分代码

int sum = 0;

for (int i = 0; i < length; i++) { 
    sum = sum + MyList[i]; 
}

cout << "The Total is: " << 
sum <<endl; int largest = MyList[0]; 

for (int i = 0; i < length; i++) 
    if ( MyList[i] > largest ) 
        cout << "The Largest Value is: " << largest <<endl; 

int smallest = MyList[0];

for (int i = 0; i < length; i++) 
    if ( MyList[i] < smallest ) smallest = MyList[I];
cout << "the Smallest Value is: " << smallest <<endl;
int和=0;
对于(int i=0;i
{
    beginning; 
    while (condition) { 
        body; 
        increment; 
    }
}
没有更多的东西可以证明。

int sum=0;
int sum = 0;
int i = 0;
while (i < length ) { 
    sum = sum + MyList[i]; 
i++;
}

cout << "The Total is: " <<sum <<endl; 
int largest = MyList[0]; 
i = 0; 
while (i < length) 
   { if ( MyList[i] > largest ) 
        cout << "The Largest Value is: " << largest <<endl; 
 i++;
}

int smallest = MyList[0];
 i = 0;
while ( i < length) 
    {
if ( MyList[i] < smallest ) smallest = MyList[I];
i++;
  }
cout << "the Smallest Value is: " << smallest <<endl;
int i=0; 而(i是的,这是可能的,但是为什么呢?首先要提高你的缩进技能,使代码可读。然后想想你是否真的需要for-to-while转换。不,将for循环转换为while循环并不会真正改变算法,它只是让它看起来有点不同。几乎每个人都知道这是可以做到的。我们只是不认为这样做有什么意义,因为它并没有真正改变任何事情。互联网上有几千个(如果不是上万个)的例子,很多好书中也有。你可能忘记了一个重要的部分:整个事情需要放在一个新的块范围内,所以嵌套在
{
}
@Someprogrammerdude谢谢,您指的是在
开始时定义的变量
在块外不“可用”?这极有可能导致
i
被误用。这只是一个何时忘记在循环之间重置
i
的问题。
int sum = 0;
int i = 0;
while (i < length ) { 
    sum = sum + MyList[i]; 
i++;
}

cout << "The Total is: " <<sum <<endl; 
int largest = MyList[0]; 
i = 0; 
while (i < length) 
   { if ( MyList[i] > largest ) 
        cout << "The Largest Value is: " << largest <<endl; 
 i++;
}

int smallest = MyList[0];
 i = 0;
while ( i < length) 
    {
if ( MyList[i] < smallest ) smallest = MyList[I];
i++;
  }
cout << "the Smallest Value is: " << smallest <<endl;