练习1.10:
#include <iostream>
int main(){
int i = 10, sum = 0;
while (i >= 0) { sum += i; --i; }
std::cout << "The sum of 10 to 0 is " << sum << std::endl;
return 0;
}
练习1.11:
#include <iostream>
/*
*比较用户输入的两个数字
*/
int compareUserTypeIn(int num1, int num2){
if (num1 > num2) {
std::cout << "用户输入的第一个数字更大" << std::endl;
return 1; //用户输入的第一个数字更大
} else if (num1 == num2) {
std::cout << "用户输入的数字一样大" << std::endl;
return 0; //用户输入的两个数字一样大
} else {
std::cout << "用户输入的第二个数字更大" << std::endl;
return -1; //用户输入的第二个数字更大
}
}
/*
*用户输入的数字进行总和的运算
*/
int sumResult(int num1, int num2, int resultCom) {
int sum = 0;
if (resultCom == 1) { //用户第一个输入的数字更大
int i = num2;
while ( i <= num1 ) {
sum += i;
++i;
}
} else if (resultCom == 0) { //用户输入的两个数字一样大
int i = num2;
while ( i <= num1 ) {
sum += i;
++i;
}
} else {
int i = num1;
while ( i <= num2 ) { //用户输入的第二个数字更大
sum += i;
++i;
}
}
return sum;
}
int main()
{
//提示用户输入两个数字
std::cout << "Please type in two numbers:" << std::endl;
int num1, num2, resultCom, sum = 0;
std::cin >> num1 >> num2;
resultCom = compareUserTypeIn(num1, num2);
sum = sumResult(num1, num2, resultCom);
std::cout << "The result is " << sum << std::endl;
return 0;
}
练习1.12
#include <iostream>
int main()
{
int sum = 0;
for (int i = -100; i <= 100; ++i)
sum += i;
std::cout << sum << std::endl;
return 0;
}
结果为0
网友评论