程序执行后,val的值变为11:
#include <iostream>
int main()
{
int sum=0,val=1;
//keep executing the while until val is greater than 10
while (val<=10){
sum+=val;
val++;
}
std::cout <<val<<std::endl;
std::cout <<"sum of 1 to 10 inclusive is "
<<sum<<std::endl;
return 0;
}
11
sum of 1 to 10 inclusive is 55
Press any key to continue
注意:修改以下程序++的位置在val++ 或者++val ,程序结果相同:#include "stdafx.h"
#include <iostream>
int main()
{
int sum=0,val;
//keep executing the while until val is greater than 10
for (val=1;val<=10;val++){
std::cout <<val<<std::endl;
sum+=val;
}
std::cout <<val<<std::endl;
std::cout <<"sum of 1 to 10 inclusive is "
<<sum<<std::endl;
return 0;
}
在val++ 中在for循环内外分别输出数值,显示为内为10 ,外为11,结果显示为55(也就是1 到10的总和) ,重新修改为++val,结果不变:
#include "stdafx.h"
#include <iostream>
int main()
{
int sum=0,val;
//keep executing the while until val is greater than 10
for (val=1;val<=10;val++){
std::cout <<val<<std::endl;
sum+=val;
}
//std::cout <<val<<std::endl;
std::cout <<"sum of 1 to 10 inclusive is "
<<sum<<std::endl;
return 0;
}
习题:1.10 1.11
#include "stdafx.h"
#include <iostream>
int main()
{
/*int sum=0,val;
//keep executing the while until val is greater than 10
for(val=50;val<=100;val++)
sum+=val;
*/
int sum=0,val=50;
while(val<=100){
sum+=val;
++val;
}
std::cout <<"sum of 50 to 100 inclusive is "
<<sum<<std::endl;
return 0;
}
#include "stdafx.h"
#include <iostream>
int main()
{
/*int sum=0,val;
//keep executing the while until val is greater than 10
for(val=50;val<=100;val++)
sum+=val;
*/
int sum=0,val=50;
while(val<=100){
sum+=val;
++val;
}
std::cout <<"sum of 50 to 100 inclusive is "
<<sum<<std::endl;
return 0;
}
#include "stdafx.h"
#include <iostream>
int main()
{
/*int sum=0,val;
//keep executing the while until val is greater than 10
for(val=50;val<=100;val++)
sum+=val;
*/
int sum=0,val=50;
while(val<=100){
sum+=val;
++val;
}
std::cout <<"sum of 50 to 100 inclusive is "
<<sum<<std::endl;
return 0;
}
while循环的条件判断跟在while后面,判断条件比较灵活,可以是各种判断。
for循环的条件也是跟在FOR后面,不过for循环多了初始条件设置,而且,for循环的条件比较适合用于参数梯级变化的情况。
在执行c++程序的时候,经常是在原程序上做修改:
不要着急,心静自然会发现问题:
最容易出现的问题是:
1 程序的输入输出部分;这个输出之前都没有把lower 和upper 当作变量来看,导致终端输入两个数子没有反映;
std::cout <<"sum of "<<lower<< " to "<< upper<< " is "
<<sum<<std::endl;
2 程序中变量的定义部分,增加了变量,那么变量是否定义呢?
3 在循环中的变化;
第一次写成了val=upper ,所以程序不能执行下去。
for(int val=lower;val<=upper;val++)
习题1.14
#include "stdafx.h"
#include <iostream>
int main()
{
std::cout<<"please enter two numbers:"<<std::endl;
int v1,v2;
std::cin >> v1 >> v2 ;
int lower,upper;
if(v1<=v2){
lower=v1;
upper=v2;
}else {
lower=v2;
upper=v1;
}
std::cout << lower <<"and"<< upper <<std::endl;
//keep executing the while until val is greater than 10
int sum=0;
for(int val=lower;val<=upper;val++)
sum+=val;
std::cout <<"sum of "<<lower<< " to "<< upper<< " is "
<<sum<<std::endl;
return 0;
}
终端显示:
please enter two numbers:
3 7 //用户输入的数字
3and7
sum of 3 to 7 is 25
Press any key to continue