使用数组和循环解决此题。定义一个大小为10的数组,数组count[i]代表每个数i。当输入数字后,对应的i++,以此记录次数。不需要记录每一个数字后统计每个数的次数。
#include <stdio.h>
int main()
{
const int number = 10//数组的大小
int x
int count[10]//定义数组
for (int i = 0i <numberi++) { //初始化数组
count[i] = 0
}
scanf_s("%d", &x)//输入x
while(x!=-1){ //当输入不为-1时,继续输入数值
if (x >= 0 &&x <= 9) {
count[x]++//数组参与运算
}
scanf_s("%d", &x)//输入x
}
for (int i = 0i <numberi++) { //遍历数组
printf("%d出现次数:%d 次\n", i, count[i])
}
}
程序运行结果
ESC按键的ascii码是十进制的27,或者是十六进制的1B,还可以是char型的'esc'。如果你是想在输入字符串时按ESC退出,那就一个个的输入字符,等到输入的字符为'esc'时跳出就好。