练习3-2 计算符号函数的值(10 分)

对于任一整数n,符号函数

### 关于统计字符的编程练习 #### Python 实现统计字符串中字符出现次数 为了统计字符串中各个字符出现的频率,Python 提供了简单的方法。通过 `str.count()` 函数可以直接获取某个特定字符在字符串里出现的数量[^1]。 ```python def count_characters(s): result = {} for char in s: if char not in result: result[char] = s.count(char) return result input_string = "hello world" character_counts = count_characters(input_string) print(character_counts) ``` 此段代码定义了一个函数`count_characters`来接收一个字符串参数`s`并返回字典形式的结果集,其中键为字符而则代表该字符在整个字符串内的重复数量。 #### Java 计算单词中各字母ASCII码之和 针对Java环境下的需求,下面展示了一种方法用于计算给定单词内部所有组成它的字母对应的ASCII数总合[^2]: ```java public class AsciiSum { public static int calculateAsciiSum(String word){ int sum = 0; for (int i = 0; i < word.length(); ++i) { sum += (int)word.charAt(i); } return sum; } public static void main(String[] args) { String testWord = "example"; System.out.println(calculateAsciiSum(testWord)); } } ``` 这段代码实现了名为`calculateAsciiSum` 的静态方法接受单个字符串作为输入,并逐一遍历其每一个字符转换成整型相加求得最终结果;另外还提供了一个简单的测试实例来进行验证。 #### C语言类统计不同类型的字符数目 最后,在C语言方面,则可以通过循环读取用户输入的一串文本数据,利用条件判断语句区出四种不同的类别——英文字母、空白符(即空格)、阿拉伯数字以及其他任何可能存在的特殊符号,并记录各自的频次[^3]。 ```c #include<stdio.h> #define MAX_LENGTH 100 void analyzeString(const char *s, int *letters, int *spaces, int *digits, int *others); int main(){ char input[MAX_LENGTH]; printf("请输入一段话:"); fgets(input,sizeof(input),stdin); int letters=0, spaces=0,digits=0,others=0; analyzeString(input,&letters,&spaces,&digits,&others); printf("\n字母:%d\n",letters); printf("空格:%d\n",spaces); printf("数字:%d\n",digits); printf("其他:%d\n",others); return 0; } // 对传入字符串进行析处理 void analyzeString(const char *s, int *letters, int *spaces, int *digits, int *others){ while(*s != &#39;\0&#39;){ if((*s>=&#39;a&#39; && *s<=&#39;z&#39;) || (*s>=&#39;A&#39;&&*s<=&#39;Z&#39;)){ (*letters)++; }else if(*s==&#39; &#39;){ (*spaces)++; }else if(*s>=&#39;0&#39;&&*s<=&#39;9&#39;){ (*digits)++; }else{ (*others)++; } s++; } } ``` 上述三个例子展示了如何根据不同编程语言的特点去解决相似的问题—统计字符信息。每一种解决方案都体现了各自的语言特性和惯用法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值