I'm looking for a bit of help and to confirm if what i'm trying to do is possible at all.
I have an array (for this test ) of 3 numbers one of them I want to use as the number to subtract by.
My starting number is 100 and I would like to leave 40 at the end as this links in to the bigger program.
I know how to loop through the array to find a matching number and have used this as a starting point, however I'm getting totally lost trying to expand this to do the above.
Any help would be greatly appreciated!
My code so far.
int main() {
int arr[3] = {12,13,60}; //Array of 3 numbers
int j = 100; // j set to 100 for the test
int t = 0; //to be used
int result;
for (int i= 0; i <= sizeof(arr); i++) { //loops through the array
if (j == arr[i] - j == 40) { //if j = array number - j == 40
possible = true;
t = arr[i] - j; //sets t to the correct array number
}
}
if (possible == 1) {
cout << "This is possible to do" << endl;
result = (j - t) << endl; //calculates the sum which leaves 40
}
else {
cout << "This is not possible" << endl;
}
return 0;
}
Like I said above I know this is not a working code however I'm totally lost as to where to turn next.
I'm not 100% clear on what you are trying to do but this looks like it is wrong:
if (j == arr[i] - j == 40) { //if j = array number - j == 40
possible = true;
t = arr[i] - j; //sets t to the correct array number
}
The if statement here means "if the current array value minus 100 is equal to 40 and 100"... which is impossible.
I think what you were looking for was:
if( j - arr[i] == 40 )
Which means "if 100 minus the current array value is 40"
I think the correct code for what you are trying to do is,
int main() {
int arr[3] = {12,13,60}; //Array of 3 numbers
int j = 100; // j set to 100 for the test
int t = 0; //to be used
int result;
for (int i= 0; i <= sizeof(arr); i++) { //loops through the array
if (j - arr[i] == 40) { //if j - array number == 40
possible = true;
t = arr[i]; //sets t to the correct array number
}
}
if (possible == true) {
cout << "This is possible to do" << endl;
cout << result = (j - t) << endl; //calculates the sum which leaves 40
}
else {
cout << "This is not possible" << endl;
}
return 0;
}
The
if (j == arr[i] - j == 40) { //if j = array number - j == 40
is surely bad. It evaluates as this:
if ((j == arr[i] - j) == 40)
Which means:
if (true == 40)
And that will be always false.
By looking at the comment
//if j = array number - j == 40
i think what you are trying to do is
if ((j=arr[i]-j) == 40){
possible=true;
t=arr[i]-j;
}
If you actually want to assign value to j and then compare it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.