我正在尝试编写一个能找到数字反转的函数,所以如果输入1234,反之则是4321。
#include <iostream>
using namespace std;
int reverse(int);
int main()
{
cout << "This is the special difference calculator. Please enter
positive integers: " << endl;
reverse();
}
int reverse(int num)
{
int num, remainder, reversenum;
cin >> num;
while (num != 0)
{
remainder = num % 10;
reversenum = reversenum * 10 + remainder;
}
return reversenum;
}
我也尝试在main中创建一个变量并将其设置为reverse(int),但它表明它是错误的。老实说,我不知道我在做什么,所以任何帮助都会非常感激!
答案 0 :(得分:0)
您仍然不明白功能如何运作。 你的逻辑错了(就我而言) 我将其编码为2位数字。 我给你留下了3,4和5位数字的数学公式。使用嵌套循环或输入操作来选择正确的方程式。阅读以下内容以了解有关功能的更多信息。 Stack Overflow不用于作业帮助,下次在寻求帮助之前更多地阅读并尝试更多代码。 阅读:http://www.cplusplus.com/doc/tutorial/functions/
#include <iostream>
using namespace std;
int rev_function (int num)
{
int r;
//For 2 digit numbers
r = (10)*(num % 10) + (num - (num % 10)) / 10 ;
//For 3 digit numbers
//f(x) = (100)(x % 10) + ((x - (x % 10)) % 100) + (x - (x % 100)) / 100
//For 4 digit numbers
//f(x) = (1000)(x % 10) + ((x - (x % 10)) % 100) * 10 + ((x - (x % 100)) % 1000) / 10 + (x - (x % 1000)) / 1000
//For 5 digit numbers
//f(x) = (10000)(x % 10) + ((x - (x % 10)) % 100) * 100 + ((x - (x % 100)) % 1000) + ((x - (x % 1000)) % 10000) / 100 + (x - (x % 10000)) / 10000
return r;
}
int main ()
{
int z;
int num;
cout << "\nThis is the special difference calculator.";
cout << "\n Please enter positive integers: ";
cin >> num;
z = rev_function (num);
cout << "The result is " << z;
}
所以输出结果为:
This is the special difference calculator.
Please enter positive integers: 12
The result is 21
答案 1 :(得分:0)
您的代码中存在一些逻辑错误。请尝试以下代码(请注意评论):
#include <iostream>
using namespace std;
int reverse();
int main()
{
cout << "This is the special difference calculator. Please enter positive integers: " << endl;
reverse();
}
int reverse()
{
int num, remainder, reversenum=0;//reversenum should be initialized to zero
cin >> num;
while (num != 0)
{
remainder = num % 10;
num = num/10; // Add this line so that while statement works correctly
reversenum = reversenum * 10 + remainder;
}
return reversenum;
}