c++ - 如何修复来自 IF/ELSE 语句的重复 cout 的输出
问题描述
我有一个完整的课程代码;它根据用户要求的字符数创建一个随机字符串,然后允许用户指定是否要在字符串中查找特定的字符对。最后一部分基于if
/else
语句,它要么给出位置,要么告诉他们字符串中没有对。
我的问题是,当给定一对查找时,如果它在字符串中它给出了更正的语句,但是,它也给出了else
重复多次的语句。如果该对不在字符串中,则它会给出正确的else
语句,但会重复cout
几次。我不知道如何解决这个问题。
这是我的代码和输出的屏幕截图。
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
int main() {
int i=0, n;
char alphabet[26];
char RandomStringArray [100];
char Ltr1, Ltr2;
srand(time(0));
cout <<"How many letters do you want in your random string (no less than 0, no more than 100): ";
cin >> n;
for (int i=0; i<=25; i++)
alphabet[i] = 'a' + i;
while(i<n) {
int temp = rand() % 26;
RandomStringArray[i] = alphabet[temp];
i++;
}
for(i=0; i<n; i++)
cout<<RandomStringArray[i];
cout<<"\n";
cout<<"What letter pair would you like to find? ";
cin>>Ltr1>>Ltr2;
for (i=0; i<n; i++)
if (Ltr1==RandomStringArray[i] && Ltr2== RandomStringArray[i+1]){
cout<<"The pair is in the string starting at character number "<<i+1<<" in the string. \n";
}
else if (Ltr1!=RandomStringArray[i] && Ltr2!= RandomStringArray[i+1])
cout<<"no";
return 0;
}
解决方案
由于您已将if...else
构造放置在for
循环内,因此每次都会对其进行评估。这意味着对于第一个条件不成立的每个实例,else
都会执行该子句,从而导致您的“否”消息重复。
推荐阅读
- c# - 在 WPF 中获取十六进制颜色代码时出错
- python - 查找字长
- asp.net - ASP.NET MVC - IIS Express(谷歌浏览器)
- acumatica - 如何在 SOLine_RowUpdated 事件中跳过基本逻辑
- php - 连接受限环境中的 PHP MySQL 连接
- java - 无法找到或加载主类 - java - gradle -
- opengl-es - 获取多个片段的 Vulkan/OpenGL 子通道
- python - sshuttle 可以使用现有的 SSH 隧道吗?
- c++ - 与同一类的私有数据成员具有相同名称的成员函数的变量会发生什么?
- groovy - 是否可以禁用属性语法以访问 groovy 中的 getter?