C++ for循环

来源:百度知道 编辑:UC知道 时间:2024/06/15 22:01:13
#include <iostream>
using namespace std;

int main()
{
int value = 2;
int pow = 10;
int result = 1;
for (int cnt = 0; cnt != pow; ++cnt)
result *= value;
cout << value
<< " raised to the power of "
<< pow << ": "
<< result << endl;
system ("PAUSE");
return 0;
}

2.
#include <iostream>

int main()
{
std::cout << "Enter base please: " <<std::endl;
int base;
std::cin >> base;
std::cout <<std::endl;

std::cout << "Enter exponent please: " <<std::endl;
int exponent;
std::cin >> exponent;
std::cout <<std::endl;

for (int times = 0; times != exponent; ++times)
result *= base;
std::cout << base
<< "released to the power of "

16 `result' undeclared (first use this function)
(Each undeclared identifier is reported only once for each function it appears in.)

这是第二个的编译结果,自己看看吧!自己调要好点。

using namespace std 和std::cout及std::cin.是一个意思!不过用命名空间的方法要方便些。

看这句
for (int times = 0; times != exponent; ++times)
result *= base;

result 事先又没定义,又没初始化,直接弄个累乘当然编译不过

undeclared的不是std是result,这两种方法在不重名的情况下是一样的(虽然第二种很繁琐,很容易输错)

但如果你不巧也有个cout和cin对象,也重载了流操作,用第一种就会有歧义,解决方法是用命名空间限定,比如你要用自己的cout,它不属于任何命名空间,就用::cout指定它.

另外::限定还用在使用基类成员上,因为C++没有什么关键字表示基类的引用(如JAVA的super或VB的mybase)它用这种方式表示请求的是基类成员.这时using namesapce XX;和XX::都是推荐的.