(1) 下面是一个计数器类的定义,请完成该类的实现,并在 main( )函数中演示该类 的应用。 class counter{ int value; public: counter(int number); void increment(); //给原值加 1 void decrement(); //给原值减 1 int getvalue(); //取得计数器的值 void print(); //显示计数器的值 };
时间: 2023-06-01 08:07:54 浏览: 25
```cpp
#include <iostream>
using namespace std;
class counter {
private:
int value;
public:
counter(int number) : value(number) {} // 构造函数
void increment() { value++; } // 给原值加1
void decrement() { value--; } // 给原值减1
int getvalue() { return value; } // 取得计数器的值
void print() { cout << "Counter value: " << value << endl; } // 显示计数器的值
};
int main() {
// 创建一个计数器对象,并演示其应用
counter c(10);
c.print();
c.increment();
c.print();
c.decrement();
c.print();
return 0;
}
```
相关问题
输入若干个字符,统计非字母的字符有多少个。当键入回车键时结束。下面 是计数器类和main函数的定义,请完成该类成员函数的实现。
class Counter {
public:
int countNonLetters() {
int count = 0;
char c;
while ((c = getchar()) != '\n') {
if (!isalpha(c)) {
count++;
}
}
return count;
}
};
int main() {
Counter counter;
int count = counter.countNonLetters();
printf("Non-letter characters count: %d\n", count);
return 0;
}
// 实现 countNonLetters 函数
int Counter::countNonLetters() {
int count = 0;
char c;
while ((c = getchar()) != '\n') {
if (!isalpha(c)) {
count++;
}
}
return count;
}
设计一个计数器类,当建立该类的对象时,其初始状态为零
以下是一个简单的计数器类的设计,初始状态为0:
```python
class Counter:
def __init__(self):
self.count = 0
def increment(self):
self.count += 1
def decrement(self):
if self.count > 0:
self.count -= 1
def reset(self):
self.count = 0
def get_count(self):
return self.count
```
其中:
- `__init__()` 方法是类的构造函数,用于初始化计数器的状态,即将计数器初值设为0。
- `increment()` 方法表示计数器加1操作,每次调用该方法,计数器的值加1。
- `decrement()` 方法表示计数器减1操作,每次调用该方法,计数器的值减1,但是不能小于0。
- `reset()` 方法表示将计数器重置为初始状态0。
- `get_count()` 方法返回当前计数器的值。
使用示例:
```python
c = Counter() # 创建计数器对象
print(c.get_count()) # 输出当前计数器的值,结果为0
c.increment() # 计数器加1
print(c.get_count()) # 输出当前计数器的值,结果为1
c.decrement() # 计数器减1
print(c.get_count()) # 输出当前计数器的值,结果为0
c.decrement() # 计数器减1,结果不变,因为已经为0
print(c.get_count()) # 输出当前计数器的值,结果为0
c.reset() # 计数器重置
print(c.get_count()) # 输出当前计数器的值,结果为0
```
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)