用c++创建一个权力表
Creating a Table of Powers with C++
我正在做一个项目,使用嵌套的for循环打印出指数表。用户指定要打印的行数和功率数。例如,如果用户指定2行和3次幂,程序应该打印1,1,1和2,4,9(2^1,2,3等)。我应该注意到这是类的,我们不允许使用cmath,否则我会使用pow()。我似乎不能在一个嵌套的for循环中找出正确的函数,它可以同时改变基数和指数的值。这是我目前所知道的。谢谢你的帮助!
#include <iostream>
#include <iomanip>
using namespace std;
int main ()
{
int r, p, a;
cout << "The program prints a table of exponential powers.nEnter the number of rows to print: ";
cin >> r;
cout << "Enter the number of powers to print: " ;
cin >> p;
cout << endl;
for (int i = 1 ; i <= r; i++)
{
cout << setw(2) << i;
for (int q = 1; q <= i; q++)
{
a = (q * q); //This only works for static numbers...
cout << setw(8) << a;
}
cout << endl;
}
}
for (int i = 1 ; i <= r; i++)
{
cout << setw(2) << i;
int a = 1;
for (int q = 1; q <= r; q++)
{
a = (a * i);
cout << setw(8) << a;
}
cout << endl;
}
有几点需要注意。首先,您可以通过保持变量a并将每个幂乘以i来计算幂。另外,我认为你应该让第二个循环的上界是r而不是I
您需要更改几次幂的累加方式。
还有,你在for循环中使用了错误的变量来结束循环。
#include <iostream>
#include <iomanip>
using namespace std;
int main ()
{
int r, p, a;
cout << "The program prints a table of exponential powers.nEnter the number of rows to print: ";
cin >> r;
cout << "Enter the number of powers to print: " ;
cin >> p;
cout << endl;
for (int i = 1 ; i <= r; i++)
{
cout << setw(2) << i;
a = 1; // Start with 1
for (int q = 1; q <= p; q++) // That needs to <= p, not <= i
{
a *= i; // Multiply it by i get the value of i^q
cout << setw(8) << a;
}
cout << endl;
}
}
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 运行同一解决方案的另一个项目的项目
- 挂起和取消挂起一个文件DLL
- 用C++中的一个变量定义一个常量
- 函数向量_指针有不同的原型,我可以构建一个吗
- 在c++中用vector填充一个简单的动态数组
- 如何在选项卡视图Qt中设置一个新项目,并保存以前的项目
- 预处理器:插入结构名称中的前一个行号
- 我在c++代码中生成了一个运行时#3异常
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- 从链接列表c++中删除一个项目
- 告诉一个 const char 数组,除了编译时 C 样式的字符串外,它不以 '