问题描述:

C++ newbie here. Anything wrong or complicated with this code? The main question I have is whether I can use v1 and v2 inside while (val <= v2)?

#include <iostream>

int main ()

{

std::cout << "Enter two numbers: " << std::endl;

int v1 = 0, v2 = 0;

std::cin >> v1 >> v2;

int sum = 0, val = v1;

while (val <= v2)

{

sum += val;

++ val;

}

std::cout << "The sum of " << v1 << " through " << v2 << " inclusive is " << sum << std::endl;

return 0;

}

网友答案:

Yes, you can, they're local variables in main() so they're in scope until main() returns (i. e. the whole lifetime of the program).

网友答案:

Of course you can. The statement inside the while-loop needs to evaluate to a boolean expression, i.e. true or false. And as you can state that either it is true that val <= v2 or not, this is perfectly fine.

相关阅读:
Top