不同的输出据我所知for
环和while
循环之间的差别看起来是这样的:WHILE循环显示出比FOR循环
为:
拳头初始化时则条件表达式检查如果结果为TRUE
那么只有语句部分得到执行,这个循环是连续的,直到条件表达式结果为FALSE
。
当:
条件表达式首先检查,如果结果TRUE
然后声明部分被执行,否则不,这个循环是连续的,直到条件表达式的结果FALSE
。
今天,我写了检查,如果string
有重复的算法,如果是只打印那些没有:
#include<stdio.h>
#include<string.h>
int main(void){
const char *str = "Mississippi";
char tmp[15] = {0};
size_t i=0,j=0,k=1;
int found=0;
tmp[0] = str[0];
printf("Before = %s\n",str);
while(str[i] != '\0'){
for(j=0;tmp[j] != '\0';j++){
if(tmp[j] == str[i]){
found++;
}
}
if(found==0){
tmp[k]=str[i];
k++;
}
found=0;
i++;
}
tmp[strlen(tmp)] = '\0';
printf("After = %s\n",tmp);
return 0;
}
输出:
Before = Mississippi
After = Misp
现在看如果替换for
循环会发生什么情况:
for(j=0;tmp[j] != '\0';j++){
if(tmp[j] == str[i]){
found++;
}
}
以`while循环:
while(tmp[j] != '\0'){
if(tmp[j] == str[i]){
found++;
}
j++;
}
我得到:
#include<stdio.h>
#include<string.h>
int main(void){
const char *str = "Mississippi";
char tmp[15] = {0};
size_t i=0,j=0,k=1;
int found=0;
tmp[0] = str[0];
printf("Before = %s\n",str);
while(str[i] != '\0'){
while(tmp[j] != '\0'){
if(tmp[j] == str[i]){
found++;
}
j++;
}
if(found==0){
tmp[k]=str[i];
k++;
}
found=0;
i++;
}
tmp[strlen(tmp)] = '\0';
printf("After = %s\n",tmp);
return 0;
}
但产量并不如预期:
Before = Mississippi
After = Misp
但是:
Before = Mississippi
After = Misisipi
为什么会发生这种情况?
TLDR;请提供一个简短而亲切的[MCVE](http://stackoverflow.com/help/mcve)来说明问题。不要发布有效的代码。 –
@WeatherVane对不起,用示例去掉了部件。 – Michi
Down Voter请解释一下,为什么?有没有机会看到谁投下了我的票? – Michi