Factoring program gets different, wrong results every time.

Hi. I'm new to C++, but I have written a similar program in Python. Every time I run the program with the same inputs, it generates different results, despite there being no random element involved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
#include <cmath>
using namespace std;

int x,y,a,b;
int *c=new int [x];
float z;

int main()
{
    cout<<"Please enter the radicand: ";
    cin>>x;
    cout<<"\nPlease enter the index: ";
    cin>>y;
    for (a=1; a<x; a++);{
        if ((x/a)==ceil(x/a));{
            c[a-1]=(x/a);
        }
    }
    cout<<c[0];
}

I am currently using the Code Blocks IDE version 10.05.

Edit: This is going to be part of a program to simplify radicals.
Last edited on
You shouldn't declare variables as global unless you absolutely have to. Your best bet is to declare a variable right before you use it. In fact, in the case of 'a', you can actually declare it inside the for statement:
 
for(int a = 0;;)

You're initializing c to store x amount of ints, but you haven't even initialized x yet. This is probably the cause of your "randomness". The program needs space for x, so it gets some, but it doesn't actually change what's already in that space until you do so manually. So x will usually be different on different runs.
The number isn't random, it's the first number entered.
I don't understand why you have used a pointer so it's hard to understand what you were trying to do, and so I don't know how to help (by the way, don't forget to use the `delete` if you use `new`. your program creates a memory leak).

As for a solution:
Could you please explain what the purpose of the program? what is it meant to do?

Side note: you should remove the semi-column (`;`) after the `if`, and `for` statement.
Last edited on
int *c=new int [x];

This is illegal, I would suggest using whatever compiler switch you need to use to make the compiler conforming.

If it weren't illegal, x is initialized to 0 (as all global variables are,) so that would be equivalent to int *c = new int[0].

As an addition to cire's post:

The proper way is:
int *c = &x;
Last edited on
Huh, cire, it's explicitly allowed to new a zero-length array, in C++ (see ยง5.3.4[expr.new]/7) It's only negative-size arrays that are illegal.
Actually, I had a brainfart. For some reason I was associating it with a VLA, which it clearly is not.
Last edited on
Topic archived. No new replies allowed.