Skip to content

Instantly share code, notes, and snippets.

@cgsdev0
Created May 12, 2019 02:38
Show Gist options
  • Save cgsdev0/4089bc5da2ed980d3ecc18a81c663329 to your computer and use it in GitHub Desktop.
Save cgsdev0/4089bc5da2ed980d3ecc18a81c663329 to your computer and use it in GitHub Desktop.
Round argv[1] to the nearest integer
/*
This program rounds argv[1] to the nearest integer.
It was tasked as a college programming assignment to one of my friends,
and written by me (in this horrifying way so he couldn't steal it and
turn it in)
*/
#include <iostream>
typedef std::runtime_error err;
int isd(char c) {
return (c^0x30)<10;
}
int main_(int argc, char** argv) {
++argv;
int _ = 0, r = 0, d = **argv-'-';
auto f = d?[](int a, int b) { return a+b; }:
[](int a, int b) { return a-b; };
if(!d) ++*argv;
while(char c = *(*argv)++)
if(!isd(c))
if(c == '.')
if(_++) goto e;
else r = f(r,(**argv-'0')>=5);
else goto e;
else if(!_) r = f(r*10, c-'0');
std::cout << r << std::endl;
return 0;
e: throw err("Invalid input!");
}
int main(int argc, char** argv) {
if(argc == 2)
try { return main_(argc, argv); }
catch(err ex) { std::cout<<ex.what()<<std::endl; }
std::cout<<"Usage: ./decToInt [decimal]"<<std::endl;
return 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment