0

Summarize the problem: My goal is to generate odd numbers up to a limit, store them in a vector then output the square of them.

Describe what you've tried: So far, I used the #include < cmath > at the start before int main(), then I used a couple of if statements to check whether the limit is zero, if so I output an error message. If the limit is >0 then I squared the odd numbers using pow(num,2) however, this does not work and gives wrong answer. For example, it gives the square of 13 as 600ish, that is obviously wrong. Please give advice. My full code is here, it is very simple so I did not put much comments in there:

#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;

    }

}
  • what is `oddnumb[i] += ++i;` supposed to be good for in the second loop? You already stored the odd numbers in the vector in the first loop – 463035818_is_not_an_ai Jul 15 '21 at 12:47
  • `oddnumb[i] += ++i;` Maybe [undefined behavior](https://stackoverflow.com/questions/4176328/undefined-behavior-and-sequence-points)? – MikeCAT Jul 15 '21 at 12:47
  • 3
    hint: (13 +13) ^2 == 676 – 463035818_is_not_an_ai Jul 15 '21 at 12:48
  • Reply to 463... is not a number: the oddnum[i] +=++i is used to generate odd numbers as it adds 2 everytime – Electrical_engineer_student Jul 15 '21 at 12:49
  • 3
    fwiw, using `pow` with integers always was wrong. See eg here: https://stackoverflow.com/questions/25678481/why-does-pown-2-return-24-when-n-5-with-my-compiler-and-os?noredirect=1&lq=1. – 463035818_is_not_an_ai Jul 15 '21 at 12:50
  • Why are you adding `++i` before calculating the pow? If you add 13 and 12 (because 12 is the index) then you calculate the pow of 25 that is exactly 625. – zerocukor287 Jul 15 '21 at 12:50
  • yes thats what you do in the first loop. In the second loop you then again add the same to each element, thats why you expect to see `13^2` but what you get is `(13+13)^2` – 463035818_is_not_an_ai Jul 15 '21 at 12:50
  • Reply to 463isnotanumber: When it stores oddnumb[i] it only seem to work within a for loop then stops working outside it. Any ideas? – Electrical_engineer_student Jul 15 '21 at 12:51
  • it only seems to work within the loop because you only assign every 2nd element of the vector. You should use a debugger to inspect waht the code does. Already printing the elements of the vector in between those two loops should explain a lot – 463035818_is_not_an_ai Jul 15 '21 at 12:52
  • How do I do this then, how to square the oddnumb[i] vector? Meanwhile I will work on the debugger to see what's happening. – Electrical_engineer_student Jul 15 '21 at 12:55
  • To square the vector, square the vector. `for (int& v : oddnumb) v *= v;` – MikeCAT Jul 15 '21 at 12:55
  • 7
    let me give you an advice: take a break. Your code and question looks like you already put a lot of effort in this but unfortunately all in the wrong direction. This has nothing to do with a change regarding cmath in C++20. Your code has parts that can only be understood as an attempt to fix something. After the break you should start again from the beginning. Fill the vector with odd elements and make sure that the vector actually has the elements you expect. Printing the vector is simple: `for (const auto& e : v) std::cout << v << " ";` – 463035818_is_not_an_ai Jul 15 '21 at 12:58
  • I wonder how you come up with this first loop. IMO this code is result of programming by permutation, what is worst possible programing technique which has a name. – Marek R Jul 15 '21 at 13:13
  • `oddnumb[i] += ++i;` is undefined behavior, and incorrect logic to begin with. What you want is probably `oddnumb[i] = i * 2 + 1;`. Also remove that line from the second loop. `i < limit-1` in the loop end condition leaves the last element zero. – Andrey Semashev Jul 15 '21 at 13:17
  • *"My full code is here"* -- please don't post your full code. Focus on a specific problem and reduce your code to a [mre]. Your goal should be **one** step not three. Determine if the problem lies in generating odd numbers up to a limit, or in storing them in a vector, or in outputing the square of them. And if the problem is in the last step (the squares), see if you can replicate the problem with a single odd number instead of the full vector. – JaMiT Jul 15 '21 at 13:18
  • Reply to JaMit: Got it. – Electrical_engineer_student Jul 15 '21 at 13:22
  • 1
    @Electrical_engineer_student You can mention/reply by using @ followed by the name. – super Jul 15 '21 at 13:52
  • 1
    Since you are using C++20, you could use `` to do something like: `auto sep = ""; for (auto n : numbers | filter(is_odd) | transform(square)) { cout << sep << n; sep = " ";} cout << "\n";` You'll have to make `is_odd` and `square` yourself, which isn't hard... `auto is_odd = [](int n) { return 1 == n % 2; };` and `auto square = [](int n) { return n * n; };` – Eljay Jul 15 '21 at 14:39
  • @Eljay thanks I will do that. – Electrical_engineer_student Jul 15 '21 at 15:13
  • @super I only started learning C++ 2 weeks ago so my coding is not very good but I am working hard on it. – Electrical_engineer_student Jul 15 '21 at 15:14
  • @463035818_is_not_a_number please give me feedback on this(I did this all by myself): https://onecompiler.com/cpp/3x5qwnvgy – Electrical_engineer_student Jul 17 '21 at 14:57

1 Answers1

1

I've written up a working version of what you want to do. I urge you to figure it out yourself first, that's the best way to learn, and then check your version against what I've got here. Note that this is certainly not the best way to do it. But I wrote it in a way that should be easy to understand. In programming there are lots of ways to tackle any problem, the best way is arguably... the way that works! Good luck in your journey with C++!

#include <cmath>
#include <iostream>
#include <vector>
int main()
{
    double input{};
    while (input < 1)//validate that input is greater than 0 here by looping if it isn't
    {
        std::cout << "Enter a limit of odd integers: ";
        std::cin >> input;
        if (input < 1)//if a valid range is entered this is never shown
        {
            std::cout << "Enter a valid range. Greater than 0. \n\n";
            std::cin.clear();
            std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        }
    }

    std::vector<double> oddNumbers{};
    std::cout << "Odd numbers:\n";
         //notice we're starting this loop at 1, since 0 is even we just avoid it
    for (double i = 1.0; i <= input; i += 2.0) //you can add more than just 1 to i
    {
        oddNumbers.push_back(i);// here we're putting the value of i at the back of the vector
        std::cout << i << " squared is " << pow(i, 2.0) << '\n';
         //we could avoid using a vector by printing the squared value of i within this loop
    }

    std::cout << "Squared Odd Numbers:\n";
         //we do need to start this loop at 0 to access the first element of the vector
    for (unsigned int i = 0; i < oddNumbers.size(); i++)
         //we also increase i by just one each time to access each element we stored
    {
        std::cout << pow(oddNumbers[i], 2.0) << '\n';
    }
    return 0;
}
Z With Glasses
  • 106
  • 1
  • 7
  • P.S. Don't feel the need to upvote this answer or accept it, I think those fellas with the comments helped point you in the right direction. I just wanted to provide this in case you got stuck and frustrated. I'm also fairly new to C++ myself so things like this are fun for me. – Z With Glasses Jul 17 '21 at 09:19
  • Hi, thanks for the answer. I tried it all by myself and got the correct answer. Let me know what you think about this one: https://onecompiler.com/cpp/3x5qwnvgy – Electrical_engineer_student Jul 17 '21 at 14:53
  • @Z With Glasses ok so that onecompiler link does not work because it can't support #include so you might want to use visual studio std latest(C++20) to run it. – Electrical_engineer_student Jul 17 '21 at 14:56
  • @Electrical_engineer_student Does it work? That's the most important part. There are best practices that are good to follow and it's always a good idea to match the format of anyone you're working with. Other than that you can always try to make code more efficient, make it easier to read, comment as you go and refactor when needed. Here's a good style guide if you're interested. https://google.github.io/styleguide/cppguide.html – Z With Glasses Jul 18 '21 at 07:42
  • Oh I should add, I'm not using preview features of c++20 with my compiler just yet so I can't compile that with std::format but the logic looks fine to me. Good job figuring it out! – Z With Glasses Jul 18 '21 at 07:53
  • Yes, yes it works well. I use visual studio 2019 with the preview features/std latest. I have will a look at the google link you sent, thanks. – Electrical_engineer_student Jul 18 '21 at 20:01