Skip to content

Instantly share code, notes, and snippets.

@rjeczalik
Last active August 29, 2015 14:07
Show Gist options
  • Save rjeczalik/90c7207d4ec18e4e24ac to your computer and use it in GitHub Desktop.
Save rjeczalik/90c7207d4ec18e4e24ac to your computer and use it in GitHub Desktop.
max - naive tool for printing maximum floating-point value from given set

Example usage:

~ $ g++ max.cc -o max
~ $ max 10 20 0 0 2 3 1 # reads input from command line
20
~ $ (echo 10; echo 20; echo 0; echo 0; echo 2) | max -i # or from stdin
20
~ $ max -0.3 -0.5 -0.1 -2.3
-0.1000
~ $ solve_linear 2 11
-5.5000
#include <iostream>
#include <cstdlib>
#include <iomanip>
#include <limits>
#include <vector>
#include <string>
using namespace std;
void die_usage() {
cerr << "usage: max [-i] [integer...]" << endl;
exit(1);
}
int main(int argc, char *argv[]) {
if (argc == 1) {
die_usage();
}
// Read input.
string line;
vector<string> lines;
if (string(argv[1]) == "-i") {
while (getline(cin, line)) {
lines.push_back(line);
}
} else {
lines = vector<string>(argv+1, argv+argc);
}
// Convert to ints.
vector<double> nums;
for (size_t i = 0; i < lines.size(); ++i) {
nums.push_back(0.0);
if (sscanf(lines[i].c_str(), "%lf", &nums[i]) != 1) {
cerr << lines[i] << " is not a valid integer" << endl << endl;
die_usage();
}
}
// Count max.
double max = -numeric_limits<double>::max();
for (size_t i = 0; i < nums.size(); i++) {
if (nums[i] > max) {
max = nums[i];
}
}
cout << fixed << setprecision(4) << max << endl;
return 0;
}
#include <iostream>
#include <cstdlib>
#include <iomanip>
#include <limits>
#include <vector>
#include <string>
#include <cmath>
using namespace std;
void die_usage() {
cerr << "usage: solve_linear [a] [b]" << endl;
exit(1);
}
bool equals(double i, double j) {
return fabs(i - j) < numeric_limits<double>::epsilon();
}
int main(int argc, char *argv[]) {
if (argc != 3) {
die_usage();
}
// Read input.
const vector<string> args = vector<string>(argv+1, argv+argc);
// Convert to ints.
vector<double> nums;
for (size_t i = 0; i < args.size(); ++i) {
nums.push_back(0.0);
if (sscanf(args[i].c_str(), "%lf", &nums[i]) != 1) {
cerr << args[i] << " is not a valid double value" << endl << endl;
die_usage();
}
}
// Solve linear and print.
if (!equals(nums[0], 0.0)) {
cout << fixed << setprecision(4) << (-nums[1]/nums[0]) << endl;
} else if (equals(nums[1], 0.0)) {
cout << "solve_linear: too many solutions for a=" << args[0] << ", b=" << args[1] << endl;
} else {
cout << "solve_linear: no solution for a=" << args[0] << ", b=" << args[1] << endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment