我正在使用switch
语句来存储用户输入的值。如果用户选择某个案例,他们会询问一个数字,并将该值存储在变量中。如果用户选择相同的情况怎么办,如何将该值添加到当前值。
我正在尝试将第一个值存储在activity_count
中,然后将值保存到activity_counts
。然后添加activity_counts
但值不断变化并继续循环更新。我知道我的逻辑错了,有人能让我更好地了解我需要做什么吗?
这是我的代码
for(daily_count = 0; daily_count < patient_count; daily_count++){
int options;
int activity_count;
int activity_counts;
cout << "1. Wash_Hands\n";
cout << "9. Exit\n";
cout << "\n";
cout << "Choose a number with a description, which best decribes patient's obsessive activities: ";
cin >> options;
cout << "\n";
switch(options){
case 1:
cout << "How much times did " << patient_name << " wash his hair:";
cin >> activity_count;
if(activity_count != 0)
activity_counts = activity_count;
activity_counts += activity_counts;
cout << activity_counts << "\n\n";
break;
default:
exit(0);
}
}
答案 0 :(得分:1)
您的代码中存在更多问题:
if (activity_count != 0)
activity_counts = activity_count;
activity_counts += activity_counts;
cout << activity_counts << "\n\n";
break;
只有触及条件后的第一个语句,其他语句总是被执行(可能缺少大括号{
和}
)
if (activity_count != 0)
似乎无用 - 添加零有什么问题?
activity_counts = activity_count;
这实际上覆盖 activity_counts
- 这是你的意思吗?
activity_counts += activity_counts;
加倍 activity_counts
为它添加相同的值 - 这是你的意思吗?
所以,我的朋友,您的代码可能至少需要这两个更改:
更改1 : Inicialize activity_counts
0
和移动{前面的声明} {1}}循环 - 使用
for
使用未初始化声明(生成 随机值 代替此部分代码 int activity_counts = 0;
for (daily_count = 0; daily_count < patient_count; daily_count++){
int options;
int activity_count;
循环中声明的变量
for
更改2 : instedad 行
for (daily_count = 0; daily_count < patient_count; daily_count++){
int options;
int activity_count;
int activity_counts;
简单地使用
if (activity_count != 0)
activity_counts = activity_count;
activity_counts += activity_counts;
(请注意,左侧有复数,右侧有单数。)