problemscpp
A collection of my answers to algorithm problems in c++.
函数
pat::b::b1054 命名空间参考

1054 求平均值 更多...

函数

int main (istream &cin, ostream &cout)
 
 TEST (b1054, case1)
 
 TEST (b1054, case2)
 

详细描述

1054 求平均值

函数说明

◆ main()

int pat::b::b1054::main ( istream &  cin,
ostream &  cout 
)

在文件 pat.cpp1836 行定义.

1836 {
1837 int n;
1838 cin >> n;
1839 string x;
1840 long double sum = 0;
1841 int k = 0;
1842 while(n-- != 0) {
1843 cin >> x;
1844 bool flag = true;
1845 int start = 0;
1846 if(x[0] == '-') {
1847 if(x.length() > 1) {
1848 start = 1;
1849 } else {
1850 goto ERROR;
1851 }
1852 }
1853 if(x.length() > 8) {
1854 goto ERROR;
1855 }
1856 if(isdigit(x[start]) != 0) {
1857 int pos = -1;
1858 for(int i = start + 1; i < x.length(); ++i) {
1859 if(x[i] == '.') {
1860 if(flag) {
1861 flag = false;
1862 pos = i;
1863 } else {
1864 goto ERROR;
1865 }
1866 } else if(isdigit(x[i]) == 0) {
1867 goto ERROR;
1868 }
1869 }
1870 if(!flag) {
1871 if(pos + 3 < x.length()) {
1872 goto ERROR;
1873 }
1874 }
1875 stringstream ss;
1876 ss << x;
1877 if(flag) {
1878 int num;
1879 ss >> num;
1880 if(num >= -1000 && num <= 1000) {
1881 sum += num;
1882 k++;
1883 } else {
1884 goto ERROR;
1885 }
1886 } else {
1887 long double num;
1888 ss >> num;
1889 if(num >= -1000 && num <= 1000) {
1890 sum += num;
1891 k++;
1892 } else {
1893 goto ERROR;
1894 }
1895 }
1896 } else {
1897 ERROR:
1898 cout << "ERROR: " << x << " is not a legal number" << endl;
1899 }
1900 }
1901 if(k == 0) {
1902 cout << "The average of 0 numbers is Undefined" << endl;
1903 } else {
1904 const long double y = sum / k;
1905 cout << "The average of " << k << " number" << (k == 1 ? "" : "s") << " is " << fixed << setprecision(2) << y << endl;
1906 }
1907 return 0;
1908 }

被这些函数引用 TEST().

◆ TEST() [1/2]

pat::b::b1054::TEST ( b1054  ,
case1   
)

在文件 pat_test.cpp810 行定义.

810 {
811 istringstream in("7\n"
812 "5 -3.2 aaa 9999 2.3.4 7.123 2.35");
813 auto out = ostringstream();
814 main(in, out);
815 const auto ans = out.str();
816 ASSERT_EQ("ERROR: aaa is not a legal number\n"
817 "ERROR: 9999 is not a legal number\n"
818 "ERROR: 2.3.4 is not a legal number\n"
819 "ERROR: 7.123 is not a legal number\n"
820 "The average of 3 numbers is 1.38\n",
821 out.str());
822 }
int main(int argc, char **argv)
Definition: main.cpp:5

引用了 main().

◆ TEST() [2/2]

pat::b::b1054::TEST ( b1054  ,
case2   
)

在文件 pat_test.cpp824 行定义.

824 {
825 istringstream in("2\n"
826 "aaa -9999");
827 auto out = ostringstream();
828 main(in, out);
829 const auto ans = out.str();
830 ASSERT_EQ("ERROR: aaa is not a legal number\n"
831 "ERROR: -9999 is not a legal number\n"
832 "The average of 0 numbers is Undefined\n",
833 out.str());
834 }

引用了 main().