C++ OJ 中多行数据输入(大小写转换、通过移位运算实现2的n次方、多组输入,每行输入数量不一样)
1. 多組輸入,輸出每行最大值
while(cin>>a>>b) 主要解決的是兩個為一組的多組數(shù)據(jù)輸入,當一次只輸入一個數(shù)據(jù)時就用 while(cin>>a)
輸入描述:
多組輸入,每行輸入包括三個整數(shù)表示的分數(shù)(0~100),用空格分隔。
輸出描述:
針對每行輸入,輸出為一行,即三個分數(shù)中的最高分。
輸入:
94 98 99
100 88 60
輸出:
99
1加粗樣式00
#include <iostream>int main()
{int a;int b;int c;int max = 0;while(std::cin >> a >> b >> c){int temp = a > b ? a : b;max = temp > c ? temp : c;std::cout << max << std::endl;}return 0;
}
2. 大小寫轉(zhuǎn)換
描述
實現(xiàn)字母的大小寫轉(zhuǎn)換。多組輸入輸出。
輸入描述
多組輸入,每一行輸入大寫字母。
輸出描述
針對每組輸入輸出對應(yīng)的小寫字母。
輸入:
A
B
輸出:
a
b
#include <iostream>int main()
{char a;while (std::cin >> a) {if(a != '\n'){std::cout << char(a + 32) << std::endl;}}return 0;
}
3. 通過移位運算實現(xiàn)2的n次方
描述
不使用累計乘法的基礎(chǔ)上,通過移位運算(<<)實現(xiàn)2的n次方的計算。
輸入描述:
多組輸入,每一行輸入整數(shù)n(0 <= n < 31)。
輸出描述:
針對每組輸入輸出對應(yīng)的2的n次方的結(jié)果。
輸入:
2
10
輸出:
4
1024
#include <iostream>int main()
{int a;while (std::cin >> a) {int result = 1 << a;std::cout << result << std::endl;}return 0;
}
4. 輸出 N*M 格式
輸入描述:
一行,輸入兩個整數(shù)n和m,用空格分隔,第二行包含n*m個整數(shù)(范圍-231~231-1)。(1≤n≤10, 1≤m≤10)
輸出描述:
輸出規(guī)劃后n行m列的矩陣,每個數(shù)的后面有一個空格。
輸入:
2 3
1 2 3 4 5 6
輸出:
1 2 3
4 5 6
#include <iostream>int main()
{int n;int m;int a;int i = 0;std::cin >> n >> m;while(std::cin >> a){i++;if(i % m != 0){std::cout << a << " ";}if(i % m == 0){std::cout << a << " " << std::endl;}}return 0;
}
5. 多組輸入,每行輸入數(shù)量不一樣
描述
首先輸入要輸入的整數(shù)個數(shù)n,然后輸入n個整數(shù)。輸出為n個整數(shù)中負數(shù)的個數(shù),和所有正整數(shù)的平均值,結(jié)果保留一位小數(shù)。0即不是正整數(shù),也不是負數(shù),不計入計算
輸入描述:
本題有多組輸入用例。首先輸入一個正整數(shù)n,然后輸入n個整數(shù)。
輸出描述:
輸出負數(shù)的個數(shù),和所有正整數(shù)的平均值。
輸入:
5
1 2 3 4 5
10
1 2 3 4 5 6 7 8 9 0
輸出:
0 3.0
0 5.0
#include <iostream>
#include <iomanip>int main()
{int n;while(std::cin >> n){int num = 0;int positive = 0;int negative = 0;double sum = 0.0;for(int i=0; i<n; i++){std::cin >> num;if(num > 0){positive++;sum += num;}if(num < 0){negative++;}}std::cout << negative << " " << std::fixed << std::setprecision(1) << (sum * 1.0)/positive << std::endl;}return 0;
}
總結(jié)
以上是生活随笔為你收集整理的C++ OJ 中多行数据输入(大小写转换、通过移位运算实现2的n次方、多组输入,每行输入数量不一样)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 2022-2028年中国非溶聚丁苯橡胶行
- 下一篇: 2022-2028年中国电容器用薄膜行业