问题描述
我有一个整数n
,代表一个常数1e<exp>
乘以<exp>
的数字。例如,对于输入数字12.345
和<exp>
为4,n = 123450
。我想尽快输出没有尾随零的原始数字。
一些潜在的(但有缺陷的)解决方案:
// Pros:
// - Very simple
// - Does not output trailing zeros
// Cons:
// - Converts to float (slow,inaccurate)
printf("%g",n * 1e-<exp>);
// Pros:
// - Quite simple
// - Uses only integer arithmetic
// Cons:
// - Outputs trailing zeros
printf("%d.%.0<exp>d",n / (int)1e<exp>,n % (int)1e<exp>);
解决方法
您的第一个朴素解决方案不适用于Resources:
MyEC2Instance:
Type: AWS::EC2::Instance
Properties:
ImageId: ami-07c8bc5c1ce9598c3
InstanceType: t2.micro
AvailabilityZone: us-east-2a
SecurityGroups:
- !Ref MySecurityGroup
MySecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: Opening port 80
SecurityGroupIngress:
- FromPort: 80
ToPort: 80
CidrIp: 0.0.0.0/0
IpProtocol: tcp
ALBListener:
Type: AWS::ElasticLoadBalancingV2::Listener
Properties:
DefaultActions:
- Type: forward
TargetGroupArn: !Ref EC2TargetGroup
LoadBalancerArn: !Ref ApplicationLoadBalancer
Port: 80
Protocol: HTTP
ApplicationLoadBalancer:
Type: AWS::ElasticLoadBalancingV2::LoadBalancer
Properties:
Scheme: internet-facing
Subnets:
- us-east-2a
- us-east-2b
SecurityGroups:
- !Ref MySecurityGroup
EC2TargetGroup:
Type: AWS::ElasticLoadBalancingV2::TargetGroup
Properties:
Name: EC2TargetGroup
Port: 80
Protocol: HTTP
Targets:
- Id: !Ref MyEC2Instance
Port: 80
VpcId: vpc-a26dcec9
Tags:
- Key: Name
Value: EC2TargetGroup
- Key: Port
Value: 80
的值大于6的情况。这是一个简单的函数。您可以相应地调整整数类型和<exp>
格式:
printf
,
我不确定这将如何执行,但是您可以尝试一下并让我们知道。
#define BUF_SZ 32
void p(unsigned n,unsigned exp)
{
char br[BUF_SZ];
int ix = BUF_SZ - 1;
br[ix--] = '\0';
while(exp)
{
// Skip trailing zeros
int t = n % 10;
n = n / 10;
exp--;
if (t)
{
br[ix--] = '0' + t;
break;
}
}
while(exp)
{
br[ix--] = '0' + n % 10;
n = n / 10;
exp--;
}
// Only insert a '.' if something has been printed
if (ix != (BUF_SZ - 2)) br[ix--] = '.';
do
{
br[ix--] = '0' + n % 10;
n = n / 10;
} while(n);
puts(&br[ix + 1]);
}
它不打印尾随零,也不打印“。”。没有小数时。
性能未知。