I want to get a count of highest number of digits from an array of decimal numbers.
For example, between 2.1 and 2.01, the resultant counter should be 2 since there are 2 digits after 2.01.
Can anyone please help me with this?
#include<conio.h>
#include<stdio.h>
#include<iostream>
using namespace std;
int main()
{
double z[100],x[100],sml;
int count=0,i=0,n;
cout<<"ENter number of elements\n";
cin>>n;
cout<<"Enter the numbers\n";
for(i=0;i<n;i++)
{
cin>>z[i];
}
x[0]=z[0]-int(z[0]);
i=0;
for(i=0;i<n;i++)
while(z[i]>=0.001&&i<n)
{
x[i]=z[i]-int(z[i]);
i++;
}
for(i=0;i<n;i++)
{
cout<<x[i]<<"\t";
}
sml=x[0];
for(i=0;i<n;i++)
if(sml>x[i])
sml=x[i];
sml=sml-int(sml);
while(sml>=0.001)
{
sml=sml*10;
count++;
sml=sml-int(sml);
}
cout<<endl<<count;
return 0;
}
It's not impossible, it should be pretty easy actually. Cast it to a string, get the substring of the results starting at the decimal and count the result.
For this you will need to look up:
-casting
-indexof
-substring
If you give it a try and can't figure out comment and I will offer you a little more guidance but you should try it yourself first.
EDIT:
I don't see much of an attempt to do what I suggested, it looks like you just posted the code you had. So here is some pseudo code for you to work with:
string stringNum = to_string(decimalNum);
int decimalPos = stringNum.find(".");
string newString = stringNum.substr(decimalPos);
int answer = newString.length();
I pretty well answered it for you, you need to figure out the syntax.
just go ahead and use this:
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main(){
float number[] = {1.234,5.64,2.001,7.11112,3.999};
int a,numAfterDecimal = 0;
for(a=0;a<sizeof(number)/sizeof(*number);a++){
ostringstream buff;
buff<<number[a];
string numStr= buff.str();
int pos = numStr.find(".");
string floatStr = numStr.substr(pos+1);
if(a == 0){
numAfterDecimal = floatStr.length();
}
else if(floatStr.length() > numAfterDecimal){
numAfterDecimal = floatStr.length();
}
}
cout << " higest number of digit after decimal is:"<< numAfterDecimal <<endl ;
}
Answer is already accepted. But just for the fun of it. Here a solution using C++ algorithms.
This will reduce the number of statements in main drastically.
Maybe it helps you to better understand modern C++
#include <iostream>
#include <string>
#include <algorithm>
#include <iterator>
#include <vector>
inline size_t getNumberOfDigitsForFraction(const std::string& s)
{
size_t positionOfDecimalPoint = s.find("."); // Look for decimal point
// And count the numbers of digits after the decimal point
return positionOfDecimalPoint == std::string::npos ? 0 : s.substr(positionOfDecimalPoint+1).size();
}
int main()
{
std::cout << "Enter the number of elements that you want to check: ";
size_t numberOfElementsToCheck{0};
// Read how many data the user wants to process
std::cin >> numberOfElementsToCheck;
// Hier we will store the values
std::vector<std::string> elements(numberOfElementsToCheck);
// Copy all wanted values from std::cin
std::copy_n(std::istream_iterator<std::string>(std::cin),numberOfElementsToCheck,elements.begin());
// Get the Element with maximum digits and print the number of digits
std::cout << "Max number of digits following decimal point: " <<
getNumberOfDigitsForFraction(
*std::max_element(elements.begin(), elements.end(),
[](const std::string &sLeft, const std::string &sRight)
{ return getNumberOfDigitsForFraction(sLeft) < getNumberOfDigitsForFraction(sRight);} )) << '\n';
return 0;
}
Related
I am writing a program to resolve the request:
Count the number of match sticks used to create numbers in each test case
Although it is a simple problem, the thing that makes me quite confusing is that the program has no error but the output is not as expected.
Source Code:
#include <bits/stdc++.h>
using namespace std;
int main() {
map<char,int> digits={
{'0',6},{'1',2},{'2',5},{'3',5},{'4',4},{'5',5},{'6',6},{'7',3},{'8',7},{'9',6}
};
map<char,int> peterMap;
int t; cin >> t;
string peterNum[t];
for(string &a:peterNum) cin >> a;
for(string b:peterNum){
int sticks = 0;
string tomNum, n;
for(char c:b) ++peterMap[c];
for(auto d:peterMap) sticks += d.second*digits[d.first];
cout << sticks << ' ';
}
return 0;
}
Input:
5 (Number of test cases)
1 0 5 10 15
Output:
2 8 13 21 28
Expected Output:
2 6 5 8 7
There are 3 problems with your code
don't use <bits/stdc++.h>, it is non-standard and promotes bad practice.
variable-length arrays are not standard C++, use std::vector instead. But this is actually not necessary in this case, because...
peterMap is completely unnecessary and needs to be removed, it is screwing up your result.
Try this instead:
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main() {
map<char,int> digits = {
{'0',6},{'1',2},{'2',5},{'3',5},{'4',4},{'5',5},{'6',6},{'7',3},{'8',7},{'9',6}
};
int t; cin >> t;
for (int i = 0; i < t; ++i) {
string a; cin >> a;
int sticks = 0;
for(char ch : a) sticks += digits[ch];
cout << sticks << ' ';
}
return 0;
}
Online Demo
Problem is here:
for(char c:b) ++peterMap[c]; // <<--here
for(auto d:peterMap) sticks += d.second*digits[d.first];
You are increasing number in map and use it in next statement without reseting for next input entry.
But there are several problems with your code:
Don't use #include <bits/stdc++.h>. I hate hackerrank for using this in their solution template.
Using string peterNum[t]; is not standard as mentioned in comments.
From my point of view, you don't need to use std::map for peterMap at least. Just iterate over characters of each string.
I have a homework assignment. The input is a three-digit number. Print the arithmetic mean of its digits. I am new to C++ and cannot write the code so that it takes 1 number as input to a string. I succeed, only in a column.
#include <iostream>
int main()
{
int a,b,c;
std::cin >> a >> b >> c;
std::cout << (a+b+c)/3. << std::endl;
return 0;
}
If you write it in Python it looks like this. But I don't know how to write the same thing in C ++ :(
number = int(input())
digital3 = number % 10
digital2 = (number//10)%10
digital1 = number//100
summ = (digital1+digital2+digital3)/3
print(summ)
The most direct translation from Python differs mostly in punctuation and the addition of types:
#include <iostream>
int main()
{
int number;
std::cin >> number;
int digital3 = number % 10;
int digital2 = (number/10)%10;
int digital1 = number/100;
int summ = (digital1+digital2+digital3)/3;
std::cout << summ << std::endl;
}
In your code, you use three different numbers and take the mean of their sum (not the sum of three-digits number). The right way is:
#include <iostream>
int main()
{
int a;
std::cin >> a;
std::cout << ((a/100) + ((a/10)%10) + (a%10))/3.<< std::endl;
return 0;
}
EDIT: This answer is incorrect. I thought the goal was to average three numbers. Not three DIGITS. Bad reading on my part
*Old answer *
I'm not sure I'm interpreting the question correctly. I ran your code
and confirmed it does what I expected it to...
Are you receiving three digit chars (0-9) and finding the average of
them? If so, I'd trying using a
for loop using getChar()
Here is a range of functions that may be of use to you.
Regex strip
Convert string to int: int myInt = stoi(myStr.c_str())
Convert int to string: std::string myStr = myInt.to_string()
If you need to improve your printing format
Using printf
If using cout, you can kindve hack your way through it!
The input is a three-digit number.
If it means, you'll be given a number that will always have 3 digits, then you can try the following approach.
Separate each digit
Find all digits sum
Divide the sum by 3
If you're given the number as a string, all you've to do is convert that string into int. Rest of the approach is the same as abve.
Sample code:
int main()
{
int a;
std::cin >> a;
int sum = (a % 10); // adding 3rd digit
a /= 10;
sum += (a % 10); // adding 2nd digit
a /= 10;
sum += (a % 10); // adding 1st digit
std::cout << (double)sum / 3.0 << std::endl;
return 0;
}
Here's a possible solution using std::string:
EDIT added digits check
#include <iostream>
#include <string>
#include <cctype>
int main()
{
std::string s;
std::cin >> s;
if(s.length() == 3 && isdigit(s[0]) && isdigit(s[1]) && isdigit(s[2]))
{
std::cout<<double(s[0] + s[1] + s[2])/3 - '0'<<std::endl;
}
else
{
std::cout<<"Wrong input"<<std::endl;
}
return 0;
}
I'm coding a program that takes user inputs and get the average of it. I need the average to always have three decimal points.
float didn't work.
some tutorials online advised to use setprecision() and fixed. That won't work because I don't know how long the number is gonna be.
Do you recommend converting the number into a string, get the length, and convert it back to double and use: setprecision(string.length+3)
Thanks
Try this :
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
float ex[] = { 0.12345, 1.2345, 12.345};
cout << setprecision(3) << fixed;
for(int i = 0; i < 3; ++i)
cout << ex[i] << endl;
return 0;
}
which gives the following output:
0.123
1.235
12.345
I recommend using the full precision of double during your calculations, and then display your final result with three decimal places.
#include <iostream>
#include <iomanip> // header file for setprecision()
using namespace std;
int main()
{
double input[4] = {1.000 , 2.0000 , 3.00 , 5.235 };
double answer = 0 , sum = 0 ;
int count = 0;
for(int i = 0; i < 3; ++i)
{
sum+=input[i];
count++;
}
answer = sum/count;
cout.precision(3);
cout << answer << endl;
return 0;
}
I am writing a program that asks the user to type in a very large int (much larger than the type int can handle). When receive this int from the user, it is stored in a string. Then, I want to convert this string into an int array (I am using a dynamic int array). After compiling and running the program, I get values that don't make sense. The values of my int array seem to be random gibberish. I don't see why this is so - it doesn't look like my loops are out of bound in the converting process. Please help. The purpose of creating an int array is to then come up with ways to add, subtract, multiply, and compare very large int values. To make it clear what I am intending to do: say the user types in "12345". I want to store this string value into an int array that would have a length of 5, each element corresponding to the next number in the int.
largeIntegers.h
#ifndef H_largeIntegers
#define H_largeIntegers
#include <iostream>
#include <string>
class largeIntegers
{
private:
void readInteger();
// reads integer
public:
std::string s_integer;
int* integer;
int length;
largeIntegers();
// default constructor
void outputInteger();
// outputs integer
};
#endif
largeIntegers.cpp
#include <iostream>
#include <string>
#include "largeIntegers.h"
using namespace std;
largeIntegers::largeIntegers()
{
readInteger();
}
void largeIntegers::readInteger()
{
int i = 0,j = 0, k;
cout << "Enter large integer: ";
cin >> s_integer;
for (; s_integer[i] != '\0'; i++);
length = i;
int* integer = new int[i];
k = 0;
for (j = i - 1; j >= 0; j--)
integer[j] = s_integer[k++] - 48;
}
void largeIntegers::outputInteger()
{
for (int i = length - 1; i >= 0; i--)
cout << integer[i];
}
User.cpp
#include <iostream>
#include <string>
#include "largeIntegers.h"
using namespace std;
int main()
{
largeIntegers a;
cout << a.length << endl << endl;
cout << a.integer[0] << endl << a.integer[1] << endl;
a.outputInteger();
cout << endl << endl;
return 0;
}
I intentionally made the variables in the header public for debugging purposes. My output on the console after compiling is:
Enter large integer: 111
3
952402760
1096565083
10966961571096565083952402760
This is the problem
int* integer = new int[i];
change to
integer = new int[i];
Your version declares a local variable that just happens to have the same name as your class variable. Easy mistake to make.
also, using standards facilities like std::vector and std::getline would make your code much cleaner in addition to avoid the problem you had, and resolve memory leaks you have now if you call readInterger twice:
void largeIntegers::readInteger()
{
cout << "Enter large integer: ";
std::getline(std::cin, s_integer);
integer = std::vector(s_integer.size());
//your last loop to fill the array probably can be replaced by std::transform
}
If i have a int say 306. What is the best way to separate the numbers 3 0 6, so I can use them individually? I was thinking converting the int to a string then parsing it?
int num;
stringstream new_num;
new_num << num;
Im not sure how to do parse the string though. Suggestions?
Without using strings, you can work backwards. To get the 6,
It's simply 306 % 10
Then divide by 10
Go back to 1 to get the next digit.
This will print each digit backwards:
while (num > 0) {
cout << (num % 10) << endl;
num /= 10;
}
Just traverse the stream one element at a time and extract it.
char ch;
while( new_num.get(ch) ) {
std::cout << ch;
}
Charles's way is much straight forward. However, it is not uncommon to convert the number to string and do some string processing if we don't want struggle with the math:)
Here is the procedural we want to do :
306 -> "306" -> ['3' ,'0', '6'] -> [3,0,6]
Some language are very easy to do this (Ruby):
>> 306.to_s.split("").map {|c| c.to_i}
=> [3,0,6]
Some need more work but still very clear (C++) :
#include <sstream>
#include <iostream>
#include <algorithm>
#include <vector>
int to_digital(int c)
{
return c - '0';
}
void test_string_stream()
{
int a = 306;
stringstream ss;
ss << a;
string s = ss.str();
vector<int> digitals(s.size());
transform(s.begin(),s.end(),digitals.begin(),to_digital);
}
Loop string and collect values like
int val = new_num[i]-'0';