如何反转实数的数字
how to reverse digits of a real no?
我知道在c中反转一个数字(整数)的数字,但我的问题是我们如何反转一个实数的数字例如,1200.23被反转为32.0021
整数代码
#include <stdio.h>
/* Iterative function to reverse digits of num(integer)*/
int reversDigits(int num)
{
int rev_num = 0;
while(num > 0)
{
rev_num = rev_num*10 + num%10;
num = num/10;
}
return rev_num;
}
/*Driver program to test reversDigits*/
int main()
{
int num = 4562;
printf("Reverse of no. is %d", reversDigits(num));
getchar();
return 0;
}
显然你的参数需要是浮点类型。
你可以将double型转换成string型,然后将string型转换回double型:
#include <string>
#include <sstream>
template<typename T>
std::string toString(T t)
{
std::stringstream ss;
ss << t;
rteurn ss.str();
}
double reversDigits(double num)
{
std::string s = std::to_string(num);
std::reverse(s.begin(), s.end());
double d;
std::stringstream ss(s);
ss >> d;
return d;
}
您可以使用以下代码,其中使用了iostream库:
#include <iostream>
#include <math.h>
using namespace std;
int main() {
double pass = 0;
double n;
double result=0;
cout << "Please enter a number to reverse" << endl;
cin >> n;
while (trunc(n / pow(10.0, pass)) > 0) {
result = fmod((n / pow(10.0, pass)), 10.0);
cout << trunc(result);
pass = pass + 1;
}
cout << endl;
system("pause");
return 0;
}
使用方法(12345/10),得到1234.5,然后截断为1234。上面的代码还使用了modulo方法('%'是取模的运算符)。例如,如果执行12345 % 10,程序将显示12345/10的余数,在本例中为5。
我在一个循环中使用这个方法来获得所需的输出。
请注意,我为一个类编写了这个程序,所以如果这不是你想要的,请忽略这篇文章。
试试这个代码-
#include <stdio.h>
#include<stdlib.h>
#include<string.h>
float reversDigits(float num)
{
char buffer[20],ch,*ptr;
int i,j,len;
snprintf(buffer,20,"%.3lf",num);
len = strlen(buffer);
for(i=0,j=len-1;i<j;i++,j--)
{
ch=buffer[i];
buffer[i]=buffer[j];
buffer[j]=ch;
}
buffer[len] = ' ';
return atof(buffer);
}
int main()
{
float num = 45000.062;
printf("Reverse of no. is %.5lfn", reversDigits(num));
return 0;
}
我在.
之后传递一个3位数的数字,所以我在snprintf
中使用%.3lf
,如果你简单地使用%lf
意味着,在将其转换为字符串的同时,它将添加零和一些数字。为了避免我使用,否则你需要做一点更多的工作来删除它!
注意:当将string转换为float或float转换为string时,它会在小数点后加一些额外的数字或零。程序员需要照顾它!
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 检查输入是否不是整数或数字
- 如何(从固定列表中)选择一个数字序列,该序列将与目标数字相加
- 如何用数字处理log(0)
- 最高有效数字侧的第N位
- 如何获取一个数字的前3位
- 查找最接近的大于当前数字的数字的索引
- 找到两对数字,使它们的乘积的绝对差最小化
- 我想做一个彼此不同但重复出现的数字
- 将数字转换为字母(例如:123 转换为一二三)
- C++如何计算用户输入的数字中的偶数位数
- 如何在C++中确定文本文件中的元素是字符还是数字
- 打印数字图案
- C++问题:用户认为数字1-100,程序提出问题不超过6次即可得到答案。无法正确
- 如何检查一个c++字符串中有多少相同的字符/数字
- 求出有多少个数字是完美平方,而sqrt()是L,R范围内的素数
- 将数字打印成文字
- 根据队列内容(if 语句)确定数字是实数还是整数
- 如何反转实数的数字