gpt4 book ai didi

c++ - 从数组中减去一个特定的数字

转载 作者:行者123 更新时间:2023-11-30 03:43:06 27 4
gpt4 key购买 nike

我正在寻求一些帮助,并确认我正在尝试做的事情是否可行。

我有一个包含 3 个数字的数组(用于此测试),我想将其中一个数字用作要减去的数字。

我的起始编号是 100,我想在最后保留 40,因为这链接到更大的程序。

我知道如何遍历数组以找到匹配的数字并将其用作起点,但是我完全迷失了尝试扩展它以执行上述操作。

如有任何帮助,我们将不胜感激!

到目前为止我的代码。

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

就像我上面说的,我知道这不是一个有效的代码,但是我完全不知道下一步该去哪里。

最佳答案

我不是 100% 清楚您要做什么,但这看起来是错误的:

    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 语句表示“如果当前数组值减去 100 等于 40 和 100”...这是不可能的。

我想你要找的是:

if( j - arr[i] == 40 )

表示“如果100减去当前数组值是40”

关于c++ - 从数组中减去一个特定的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36331714/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com