Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/132.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循环不停止_C++_For Loop_Compiler Errors - Fatal编程技术网

C++ For循环不停止

C++ For循环不停止,c++,for-loop,compiler-errors,C++,For Loop,Compiler Errors,我在一个不会停止的函数中有一个for循环。 以下是整个功能,用于查找一个人的分数,将其相加,然后在屏幕上显示平均值: float Student::average() { cout << "How many grades would you like to enter? (Up to ten)\n"; float x; cin >> x; cout << "What is your first grade?"; cin >

我在一个不会停止的函数中有一个for循环。 以下是整个功能,用于查找一个人的分数,将其相加,然后在屏幕上显示平均值:

float Student::average() { 
   cout << "How many grades would you like to enter? (Up to ten)\n";
   float x;
   cin >> x;

   cout << "What is your first grade?";
   cin >> grade[0];
   int i = 1;
   for (i; i = x; i++) {
      cout << "What is the next number?\n";
      cin >> grade[i];
   }
   averageGrade = std::accumulate(grade, grade+10, 0.0);
   averageGrade = averageGrade / 10;

   return averageGrade;
}
float Student::average(){
cout>x;
cout>等级[0];
int i=1;
对于(i;i=x;i++){
cout>grade[i];
}
平均等级=标准::累计(等级,等级+10,0.0);
平均等级=平均等级/10;
返回平均等级;
}
下面是for循环本身:

for (i; i = x; i++) {
   cout << "What is the next number?\n";
   cin >> grade[i];
}
(i;i=x;i++)的
{
cout>grade[i];
}
错误也会输出(但仍允许程序运行)如下:

1> c:\users\hastudent\documents\visual studio 2008\projects\Wearms\Wearms.cpp(25):警告C4244:“=”:从“float”转换为“int”,可能会丢失数据

1> c:\users\hastudent\documents\visualstudio 2008\projects\wearms\wearms\wearm.cpp(30):警告C4244:“=”:从“double”转换为“float”,可能会丢失数据


程序会一直到要求输入下一个数字的时候。然后你输入数字,它会一直问你这个问题。

循环应该是:

for (int i = 1; i < x; i++)
for(int i=1;i

现在(
i=x
)是将
x
赋值给
i
,而您可能打算进行比较。在这种情况下,要使用的正确比较是“小于”(
i
)。

是否尝试在for循环中打印i的值?从x开始,并不断递增

这可能是:

for(int i=0; i<x; i++) { /* do something */ }

for(int i=0;ifor循环永远运行,因为:

  • i=x是一个赋值,而不是相等测试
  • 它的值是左侧的值
  • 你给了它非零值
  • 和非零值在C++中是真的。

如果需要相等测试,请使用==。但是,在这种情况下,您需要测试。

循环的
第二部分是“何时继续”条件,而不是“何时停止”

由于您从索引1开始(非常规但在C++中并非闻所未闻),因此应该迭代到所讨论的数字:


for(i=1;i使用!=(比较运算符)而不是=(赋值运算符)在for循环中,

btw是警告,而不是错误。您应该使用<代码> int >代码> <代码> x>代码>;我认为不可能进入一个等级的一半。而且,您应该认真考虑为变量使用更多描述性的名称。使用<代码> i <代码>计数器是很好的,但是用<代码> Noths x<代码>。ode>将使代码更易于阅读。实际上,我以前有numGrades,但为了便于使用,我对其进行了更改。此外,for循环现在可以工作,但现在每当它显示averageGrade时,控制台都只显示其内存地址。@ChrisMP:我们无法更正显示代码,因为您没有向我们显示它。这在显示ar时很常见雷。你确定你只打印了一个变量吗?@MooingDuck所做的只是一个简单的cout+1:中间的子句是“只要是这样”,而不是“直到这样”…即使是这样,OP的意思是
==
而不是
=
。我的索引是从零开始的。在for循环开始之前查看代码。