编程之美 焦距

<span style="font-size:18px;">#include <iostream>
#include <fstream>
#include <string>
using namespace std;

double change(string s) {
    //cout<<s<<endl;
    double value;
    if(s.at(s.length()-1) == 'm' && s.at(s.length()-2) == 'd') {
        // dm
        value = atof(s.substr(0,s.length()-2).data());
        value *= 100;
    }else if(s.at(s.length()-1) == 'm' && s.at(s.length()-2) == 'c') {
        // cm
        value = atof(s.substr(0,s.length()-2).data());
        value *= 10;
    }else if(s.at(s.length()-1) == 'm' && s.at(s.length()-2) == 'm') {
        // mm
        value = atof(s.substr(0,s.length()-2).data());
    }else if(s.at(s.length()-1) == 'm' && s.at(s.length()-2) == 'u') {
        // um
        value = atof(s.substr(0,s.length()-2).data());
        value /= 1000;
    }else if(s.at(s.length()-1) == 'm' && s.at(s.length()-2) == 'n') {
        // nm
        value = atof(s.substr(0,s.length()-2).data());
        value /= 1000*1000;
    }else if(s.at(s.length()-1) == 'm' && s.at(s.length()-2) != 'm') {
        // m
        value = atof(s.substr(0,s.length()-1).data());
        value *= 1000;
    }else {
        // px
        value = atof(s.substr(0,s.length()-2).data());
    }
    return value;
}

int main(int argc, const char * argv[]) {
    ifstream in("/Users/urey/data/input");
    int T;
    in >> T;
    for (int i = 0; i < T; ++i){
        string s1,s2,s3;
        in>>s1>>s2>>s3;
        double ff = change(s1);
        double cc = change(s2);
        double ii = change(s3);
        double result = ii * ff / cc;
        cout<<"Case "<<i+1<<": ";
        cout.setf(ios::fixed);
        cout.precision(2);
        cout<<result<<endl;
    }
    return 0;
}</span>


(1)string转数值型,比如string转double,atof

(2)string转const char*,string.data()

(3)保留两位小数:cout.setf(ios::fixed),cout.precision(2);

    原文作者:qwurey
    原文地址: https://blog.csdn.net/yeruby/article/details/44892269
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞