怀疑C ++中的precision()函数 [英] Doubt regarding precision( ) function in C++
问题描述
给定一个大小为n且多个值的数组,我们需要左右旋转数组。
输入:
第一行由T测试案例组成。每个测试用例的第一行由N和K组成,N表示数组元素的数量,K表示要移位的位数。每个测试用例的第二行由数组元素组成。
输出:
单行输出,打印旋转的数组。
约束条件:
1< = T< = 100
1< = N< = 10 ^ 4 >
1< = K< = 10 ^ 4
示例:
输入:
1
5 14
1 3 5 7 9
输出:
9 1 3 5 7 >
我的代码附在这里,虽然我得到了正确的答案但是在期望的输出和预期的输出(关于使用精度函数)方面存在细微差别(.000004),什么我应该在这里修改吗?
我尝试了什么:
我的代码是 -
Given an array of size n and multiple values around which we need to left rotate the array.
Input:
First line consists of T test case. First line of every test case consists of N and K, N denoting number of elements of array and K denoting the number of places to shift. Second line of every test case consists of elements of array.
Output:
Single line output, print the rotated array.
Constraints:
1<=T<=100
1<=N<=10^4
1<=K<=10^4
Example:
Input:
1
5 14
1 3 5 7 9
Output:
9 1 3 5 7
My code is attached here , although I am getting right answer but there is slight difference(.000004) in desired output and expected output (its regarding use of precision function), what should I modify here?
What I have tried:
My code is-
#include<iostream>
#include<cmath>
#include<iomanip>
using namespace std;
int main()
{
int t;
cin>>t;
while(t--)
{
int set_size,i;
cin>>set_size;
int arr[set_size];
for(i=0;i<set_size;i++)
{
cin>>arr[i];
}
unsigned int pow_set_size = pow(2, set_size);
int counter, j;
float sum_avg=0;
cout<<fixed<<setprecision(6);
/*Run from counter 000..0 to 111..1*/
for(counter = 0; counter < pow_set_size; counter++)
{
float avg,sum=0;int no=0;
for(j = 0; j < set_size; j++)
{
/* Check if jth bit in the counter is set
If set then pront jth element from set */
if(counter & (1<<j))
{
// cout<<arr[j];
sum+=arr[j];
no++;
// int no=0,sum=0,digit;
// float avg;
// while(arr[j]!=0)
// {
// digit=arr[j]%10;
// sum=+digit;
// arr[j]/=10;
// no++;
//
// }
// avg=sum/no;
//
//
// overall_sum+=avg;
// cout<<"overall_sum="<<overall_sum<<endl;
}
}
if(sum!=0)
{avg=sum/no;
cout<<"avg= "<<avg;
sum_avg+=avg;
}
cout<<endl;
}
// cout<<fixed<<setprecision(6);
cout<<sum_avg<<endl;
}
return 0;
}
//1
//3
//2 3 5
//Its Correct output is:
//23.333333
//And Your Output is:
//23.333334
推荐答案
计算机上的浮点数通常是近似值,它们的精度取决于它们是单长度值还是双倍长度值。请参阅每个计算机科学家应该知道的关于浮点运算的内容 [ ^ ]。
Floting point numbers on a computer are usually approximations, and their precision depends upon whether they are single or double length values. See What Every Computer Scientist Should Know About Floating-Point Arithmetic[^].
这篇关于怀疑C ++中的precision()函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!