C++ 循环初始值设定项和计数器

c++ loop initializer and counters

本文关键字:计数器 循环 C++      更新时间:2023-10-16
#include <iostream>
using namespace std;
int main()
{
int score;
int numTests;
int total = 0; //why total has to be set to 0
double average;
cout << "How many tests: ";
cin >> numTests;
int s = 1;  
while (s <= numTests)  
{
cout << "Enter score # " << s << ": "; // why put the s there ???
cin >> score;
total += score; 
s++;    //why update the counter 
}
cout << "total" << total << endl;
average = (double)total / numTests;
cout << "Average" << average << endl; 
system("pause");
return 0;
}

1.My 问题是,为什么整数总数必须作为值 0?(整数总计 = 0(

2.在我输入分数数字的行上,为什么我必须在上面输入计数器?(<<"输入分数 # "<<s <<(

3.为什么我要更新计数器(s++(?

问题 1. 在 C++ 和 C 中,当您定义变量时,值的默认值是内存中的任何值,并且不为 null 或 0

问题 2. cout<<用于打印数据和您编写 cout 时<<p>问题 3. s++ 表示 s=s+1;这是针对循环端的,而 (s <= numTests(

  1. 在开始计算测试分数之前,总数自然是 0。

  2. 您放置计数器 s 以指示应输入哪个分数,即"分数 1"、"分数 2"等......它是为了澄清用户。想象一下,你在另一边,想看看你从 20 次测试中得到的平均值,但每次它只显示:"输入分数:" - 首先,你不确定它是否有效,其次,在某些时候你可能会分心并忘记你输入了多少分数。因此,这准确地显示了您所在的位置。

  3. s++ 表示计数器每次增加 1 时。因此,当它达到测试次数时,循环将不会继续。计数器用作 while 循环的条件 - 因此循环将停止并且不会无限期地进行。