习题 1.17 编写程序,要求用户输入一组数,输出信息说明其中有多少负数。
#include "stdafx.h"
#include <iostream>
int main()
{
int amount=0,value;
while(std::cin>>value)
if (value<=0)
++amount;
std::cout<<"the number of negative value is "<< amount <<std::endl;
return 0;
}
2
3
4
-2
s
the number of negative value is 1
Press any key to continue
习题1.18 编写程序,提示用户输入两个数,并将这两个数范围内的每个数写到标准输出。发现第一次写的程序没有考虑到数字大小颠倒的情况。#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<<" the number between "<< lower<<" and "<< upper<<" : "<<std::endl;
for (int i=lower; i<=upper; i++) {
std::cout<< i <<std::endl;
}
return 0;
}
调试显示:
Please enter two numbers:
6 2
the number between 2 and 6 :
2
3
4
5
6
Press any key to continue
习题1.19 如果上题给定数1000 和 2000,程序将产生什么结果?修改程序,使每一行输出不超过10个数。
#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<<" the number between "<< lower<<" and "<< upper<<" : "<<std::endl;
for (int i=lower,j=0; i<=upper; ++i) {
std::cout<< i <<" ";
++j;
if (j==10) {
j=0;
std::cout<<std::endl;
}
}
return 0;
}
Please enter two numbers:
1000 2000
the number between 1000 and 2000 :
1000 1001 1002 1003 1004 1005 1006 1007 1008 1009
............
1990 1991 1992 1993 1994 1995 1996 1997 1998 1999
2000 Press any key to continue
总结:可以在for 循环中添加输出行;
达到换行目的:可以采用计数,每10个可以输出std::cout<<std::endl;
同时输出一个数字后,需要输出“ ”以便与另一个数字隔开。
开始学习的时候,想到程序不知道用什么实现,觉得蛮神秘的,但是后来发现答案全部是已经掌握的知识,而不是需要新知识。也增加了对于概念的理解。
习题1.20 编写程序,求用户指定范围内的数的和,省略设置上界和下界的if测试。假定输入数是7和3,按照这个顺序,预测程序运行结果。然后按照给定的数是7和3运行程序,看结果是否与你预测的相符。如果不相符,反复研究关于for和while循环的讨论直到弄清楚其中的原因。
#include "stdafx.h"
#include <iostream>
int main()
{
std::cout<<"Please enter two numbers:"<<std::endl;
int v1,v2;
std::cin>>v1>>v2;
int sum=0;
for (int i=v1; i<=v2; i++) {
sum+=i;
}
std::cout<<"the sum between "<< v1 << " to "<< v2 << " is:"<< sum <<std::endl;
return 0;
}
Please enter two numbers:
7 3
the sum between 7 to 3 is:0
Press any key to continue
后来执行完毕结果为0 的原因是 :
对于for循环,i的初始值为 7 ,判断i小于3为假 ,for语句不执行,结果为0 。