首页 › 题库 › C/C++编程考级 › C/C++编程五级 › 简答题
简答题 适中
#23969

实数验证

实数验证

未登录也能判分,登录后才会记录
答案与解析
正确答案:<pre class="brush:cpp;toolbar:false;">#include &lt;iostream&gt; #include &lt;string&gt; #include &lt;vector&gt; using namespace std; int main() {     string s;     getline(cin, s);     bool bad1 = false, bad2 = false, bad3 = false, bad4 = false;     // 规则4:只能是 0-9 . + -     for (char ch : s)     {         if (!(isdigit(ch) || ch == '.' || ch == '+' || ch == '-'))         {             bad4 = true;             break;         }     }     // 规则1:+ - 只能在第一个,最多一个     int sign_cnt = 0;     for (int i = 0; i &lt; s.size(); i++)     {         if (s[i] == '+' || s[i] == '-')         {             sign_cnt++;             if (i != 0)             {                 bad1 = true;             }         }     }     if (sign_cnt &gt; 1) bad1 = true;     // 规则2:小数点最多一个     int dot_cnt = 0;     for (char ch : s)     {         if (ch == '.') dot_cnt++;     }     if (dot_cnt &gt; 1) bad2 = true;     // 规则3:整数、小数部分不能同时为空,至少有一位数字     bool has_digit = false;     for (char ch : s)     {         if (isdigit(ch))         {             has_digit = true;             break;         }     }     if (!has_digit)     {         bad3 = true;     }     else     {         // 有小数点的时候,不能两边都没有数字         if (dot_cnt == 1)         {             int pos = s.find('.');             bool left_has = false, right_has = false;             for (int i = 0; i &lt; pos; i++)             {                 if (isdigit(s[i])) left_has = true;             }             for (int i = pos + 1; i &lt; s.size(); i++)             {                 if (isdigit(s[i])) right_has = true;             }             if (!left_has &amp;&amp; !right_has)             {                 bad3 = true;             }         }     }     vector&lt;int&gt; err;     if (bad1) err.push_back(1);     if (bad2) err.push_back(2);     if (bad3) err.push_back(3);     if (bad4) err.push_back(4);     if (err.empty())     {         cout &lt;&lt; "Valid\n";     }     else     {         cout &lt;&lt; "Invalid\n";         for (int i = 0; i &lt; err.size(); i++)         {             if (i &gt; 0) cout &lt;&lt; ' ';             cout &lt;&lt; err[i];         }         cout &lt;&lt; '\n';     }     return 0; }</pre>
这道题暂未补解析。