除了 'x++' 或 'x--' 之外,我能否在 C++ 中做更多的事情?
Can I do in c++ something more than just 'x++', or 'x--'?
我在这里制作了一个程序来做 3x+1 数学题。所以我想问,我是否可以用 C++ 代码编写类似 x/2;
或 x*3+1
的代码。我放在这里的这些东西有错误。那么,在 C++ 中有可能做到这一点吗?如果是,如何?
代码如下:
#include <iostream>
using namespace std;
int main() {
cout << "Write an integer.\n"; int x; cin >> x;
// I made here a program to do 3x+1 math problem.
while (x==1) {
if ((x%2)==0) {
x/2; cout << x << ", ";
} else if ((x%2)==1) {
x*3+1; cout << x << ", ";
}
}
return 0;
}
那里的输出是:
/tmp/GjudkYOaE4.o
Write an integer.
9
但我正等着它写数字 28、14 等等,但它什么也没做。
使用赋值运算符 ('=') 为同一个变量赋值:
x = x*3+1;
或
x = x/2;
我看得出您是编码新手,建议您阅读大量有关您正在使用的 if-elseif-else
和 while loop
的信息
我可以在这里告诉你一些更正
#include <iostream>
using namespace std;
int main() {
cout << "Write an integer.\n";
int x; cin >> x;
// I made here a program to do 3x+1 math problem.
while (x!=1) { // x!=1 could be one of the terminating condition so when your x becomes 1, the loop would end. But of course the terminating condition depends on what you are trying to achieve
if (x % 2 == 0) {
x = x/2; //you need to assign the value back to x
cout << x << ", ";
} else { // you dont need else-if here because there could only be 2 possibilities for %2 operaion here
x = x*3+1;
cout << x << ", ";
}
}
return 0;
}
我在这里制作了一个程序来做 3x+1 数学题。所以我想问,我是否可以用 C++ 代码编写类似 x/2;
或 x*3+1
的代码。我放在这里的这些东西有错误。那么,在 C++ 中有可能做到这一点吗?如果是,如何?
代码如下:
#include <iostream>
using namespace std;
int main() {
cout << "Write an integer.\n"; int x; cin >> x;
// I made here a program to do 3x+1 math problem.
while (x==1) {
if ((x%2)==0) {
x/2; cout << x << ", ";
} else if ((x%2)==1) {
x*3+1; cout << x << ", ";
}
}
return 0;
}
那里的输出是:
/tmp/GjudkYOaE4.o
Write an integer.
9
但我正等着它写数字 28、14 等等,但它什么也没做。
使用赋值运算符 ('=') 为同一个变量赋值:
x = x*3+1;
或
x = x/2;
我看得出您是编码新手,建议您阅读大量有关您正在使用的 if-elseif-else
和 while loop
的信息
我可以在这里告诉你一些更正
#include <iostream>
using namespace std;
int main() {
cout << "Write an integer.\n";
int x; cin >> x;
// I made here a program to do 3x+1 math problem.
while (x!=1) { // x!=1 could be one of the terminating condition so when your x becomes 1, the loop would end. But of course the terminating condition depends on what you are trying to achieve
if (x % 2 == 0) {
x = x/2; //you need to assign the value back to x
cout << x << ", ";
} else { // you dont need else-if here because there could only be 2 possibilities for %2 operaion here
x = x*3+1;
cout << x << ", ";
}
}
return 0;
}