Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <stdlib.h>
- #include <math.h>
- #include <vector>
- #include <algorithm>
- using namespace std;
- // Auxiliary Function
- vector <int> binary(int n){
- int numOfDigits = int(log(n) / log(2)) + 1;
- // 3. Check the case of 0 or the overflow case
- if(n > INT_MAX){
- cout << "Cannot make calculations with numbers higher than: " << INT_MAX << endl << endl;
- }
- vector <int> digits = vector <int> ();
- int sum = n;
- for(int i=numOfDigits-1; i>=0; i--){
- if(sum >= pow(2, i)){
- digits.push_back(1);
- sum -= pow(2, i);
- }
- else{
- digits.push_back(0);
- }
- }
- return digits;
- }
- int main()
- {
- // 1. Intro
- cout << "Welcome to the A/D Converter!\n\n";
- cout << "1. Give me the Reference Voltage (V_ref): ";
- double V_ref;
- cin >> V_ref;
- while(V_ref <= 0){
- cout << "Non-positive V_ref is not acceptable.\n";
- cout << "Give me the Reference Voltage (V_ref): ";
- cin >> V_ref;
- }
- cout << "\n2. Now give me how many digits the transformed binary word must have (up to 2).\n";
- cout << "Number of digits: ";
- int numOfDigits;
- cin >> numOfDigits;
- while(numOfDigits < 2){
- cout << "Number of digits: ";
- cin >> numOfDigits;
- }
- cout << "\n3. Last step is to give me the voltage you count with your polymeter to convert it into binary word (V_count).\n";
- double V_count;
- cin >> V_count;
- while(V_count < 0 || V_count > V_ref){
- cout << "Give me the voltage you count with your polymeter to convert it into binary word (V_count).\n";
- cin >> V_count;
- }
- // 2. Convert
- double step = V_ref / (pow(2, numOfDigits) - 1);
- vector <double> voltages = vector <double> ();
- for(double voltage=0; voltage<=V_ref; voltage+=step){
- voltages.push_back(voltage);
- }
- int indexNumber = -1;
- for(unsigned int i=0; i<voltages.size(); i++){
- if(voltages[i]-step/2 <= V_count && V_count < voltages[i]+step/2){
- indexNumber = i;
- }
- }
- cout << V_count << " ---> ";
- vector <int> digits = binary(indexNumber);
- unsigned int digitsSize = digits.size();
- // Complete with zeros when necessary
- for(unsigned int i=0; i<numOfDigits-digitsSize; i++){
- cout << "0";
- }
- // Display the vector "digits"
- for(unsigned int i=0; i<digitsSize; i++){
- cout << digits[i];
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement