【发布时间】:2021-07-15 12:41:29
【问题描述】:
总结问题: 我的目标是生成一个限制的奇数,将它们存储在一个向量中,然后输出它们的平方。
描述您的尝试: 到目前为止,我在 int main() 之前的开头使用了 #include ,然后我使用了几个 if 语句来检查限制是否为零,如果是则输出错误消息。如果限制> 0,那么我使用 pow(num,2) 对奇数进行平方,但是,这不起作用并给出错误的答案。例如,它给出 13 的平方为 600ish,这显然是错误的。请给建议。我的完整代码在这里,它很简单,所以我没有放太多的cmets:
#include<iostream>
#include<format>
#include<cmath>
#include<vector>
using namespace std;
int main()
{
int limit{};
cout << "Enter a limit of odd integers: \n";
cin >> limit;
vector<int>oddnumb(limit);
if (limit == 0)
{
cout << "You MUST enter a number>0, then restart the program. \n";
return 0;
}
if (limit > 0)
{
cout << "Odd numbers are as follows: \n";
for (size_t i{}; i < limit-1; ++i)
{
oddnumb[i] += ++i;
cout << oddnumb[i] << endl;
}
cout << "Squared odd numbers follow: \n";
for (size_t i{}; i < limit - 1; ++i)
{
oddnumb[i] += ++i;
cout << pow(oddnumb[i],2) << endl;
}
}
【问题讨论】:
-
提示:(13 +13) ^2 == 676
-
fwiw,将
pow与整数一起使用总是错误的。参见例如:stackoverflow.com/questions/25678481/…. -
让我给你一个建议:休息一下。您的代码和问题看起来您已经为此付出了很多努力,但不幸的是,所有这些都朝着错误的方向发展。这与 C++20 中有关 cmath 的更改无关。您的代码中的某些部分只能被理解为尝试修复某些东西。休息后,你应该从头开始。用奇数元素填充向量,并确保向量实际上具有您期望的元素。打印矢量很简单:
for (const auto& e : v) std::cout << v << " "; -
@Electrical_engineer_student 您可以使用@后跟名称来提及/回复。
-
由于您使用的是 C++20,因此您可以使用
<ranges>执行以下操作:auto sep = ""; for (auto n : numbers | filter(is_odd) | transform(square)) { cout << sep << n; sep = " ";} cout << "\n";您必须自己创建is_odd和square,这不是很难...auto is_odd = [](int n) { return 1 == n % 2; };和auto square = [](int n) { return n * n; };