Answer the question
In order to leave comments, you need to log in
Find the number 7 in a number from 100 to 1000?
I just started learning C++ and here is a problem. You need to generate 15 numbers from 100 to 1000 (including fractional ones) and output 15 numbers that contain the number 7.
But when compiling, the compiler writes:
1.cpp: In function ‘int main()’:
1.cpp:13:14: error: invalid operands of types ‘int’ and ‘double’ to binary ‘operator%’
13 | r = rand() % 1000.0 + 100.0;
| ~~~~~~ ^ ~~~~~~
| | |
| int double
1.cpp:16:8: error: invalid operands of types ‘double’ and ‘int’ to binary ‘operator%’
16 | if(r % 10 == 7){
| ~ ^ ~~
| | |
| | int
| double
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main(){
srand(time(0));
float r;
int iter = 0;
int seven = 0;
while (true){
r = rand() % 1000.0 + 100.0;
iter++;
if(r % 10 == 7){
cout << r << endl;
seven++;
}
if (iter == 1000 || seven == 15){
break;
}
}
return 0;
}
Answer the question
In order to leave comments, you need to log in
You need to generate 15 numbers from 100 to 1000 (including fractional ones) and output 15 numbers that contain the number 7.
#include <iostream>
#include <vector>
#include <string>
#include <random>
#include <algorithm>
#include <iterator>
#include <iomanip>
#include <limits>
using namespace std;
// Не важно, пусть будет так.
auto getNRandomNumbersVecFromRange(const double low, const double hi, const int n){
random_device rd;
mt19937 gen(rd());
uniform_real_distribution<> dis(low, hi);
vector<double> randNumbersVec(n);
generate_n(randNumbersVec.begin(), n, [&dis, &gen]{ return dis(gen); });
return randNumbersVec;
}
int main()
{
auto numbers = getNRandomNumbersVecFromRange(100.0, 1000.0, 15);
cout << setprecision(numeric_limits<double>::digits10 + 1);
copy(numbers.cbegin(), numbers.cend(), ostream_iterator<double>(cout, "\n"));
cout << "\n" << "result:" << "\n"; // "\nresult\n"
// А это важно --> to_string(n).find('7') != string::npos
copy_if(numbers.cbegin(), numbers.cend(),
ostream_iterator<double>(cout, "\n"),
[](auto n) { return to_string(n).find('7') != string::npos; });
}
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main() {
srand(time(0));
int r;
int iter = 0;
int seven = 0;
while (true) {
r = rand() % 1000 + 100;
iter++;
if (r % 10 == 7) {
cout << r << endl;
seven++;
}
if (iter == 1000 || seven == 15) {
break;
}
}
return 0;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question