【问题标题】:C++ nested loop, increasing base by powerC ++嵌套循环,通过幂增加基数
【发布时间】:2015-12-28 23:39:43
【问题描述】:

我需要一些帮助。我想达到我的图像上显示的结果result

第一个问题...我的老师有没有弄错? 2^10 = 1024 而不是 2048...?!但是非虚拟机..

我唯一的问题是超过 100.000 的数字 - 请帮助

这是我目前的代码

#include <iostream>
#include <math.h>
#include <iomanip>
#include <string>
#include <sstream>
#include <ostream>
#include <stdio.h>
#include <conio.h>
#include <fstream>

using namespace std;

int main() {
    int p;      // exponent
    float b;    // base

    cout << setw(4);
    for (b=1; b<11; b++) {
        cout << " | " << setw(12) << b;
    }
    cout << endl;
    for (b=1; b<=10; b++) {
        cout << b;  
        for (p=1; p<=10; p++) {
            cout << " | " << setw(12) << pow(b, p);
        }
        cout << endl;
    }
    return 0;
}

这个的输出是here

请帮忙,

最好的问候!

【问题讨论】:

  • 哦,还有...谁能告诉我我不需要哪些包含?我刚刚从我看过的教程中添加了一些......正如我所说,我是 C++ 新手,通常我是一名网页设计师 - 所以没有太多编程:/
  • @Rellston 数字没有问题。它们是用科学记数法写的。是这个问题吗?
  • 第一个表的第二行似乎是错误的(假设您想要 row^col),因为 2^3=8 而不是 16(所以实际上该行的其余部分应该转移到对,因此以 2^10=1024 结尾)。
  • 感谢超级快速的回复!我的号码有什么问题?在我的输出图像中,您可以看到 10^10 = 1e+010 而不是我预期的:10000000000!
  • @Rellston 你知道 1e+010 10000000000,对吗?是格式错误,而不是结果错误。

标签: c++ nested-loops long-integer


【解决方案1】:

如果问题是输出,那么最简单的做法是将 pow() 返回值转换为 long long 或任何编译器的 64 位 int 类型。

这将自动为operator &lt;&lt; 使用long long 重载,这将有效地删除科学记数法。

 for (p=1; p<=10; p++) {
    cout << " | " << static_cast<long long>(pow(b, p));

Live Example

【讨论】:

  • 是的,只有输出才是问题所在:D 非常感谢 - 现在完美运行!!! @PaulMcKenzie
猜你喜欢
  • 2020-06-14
  • 1970-01-01
  • 2013-08-04
  • 2014-02-11
  • 1970-01-01
  • 1970-01-01
  • 2020-10-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多