【发布时间】:2021-05-23 20:23:00
【问题描述】:
我编写了一个代码,可以打印出用户输入字符串中有多少个 a。
我希望程序打印出“总共有 1 个 a”而不是“总共有 1 个 a”。
我尝试编写一个 if 语句,但它会在每个循环中打印出字符串的长度。我该如何调整这个?我已经尝试了一些东西,但我没有做到这一点。
#include <stdio.h>
#include <cs50.h>
#include <string.h>
int main(void){
int count = 0;
string input = get_string("Write something and I'll tell you how many a's there are: ");
for (int i = 0, n = strlen(input); i < n ; i++){
if (input[i] == 'a' || input[i] == 'A'){
count++;
}
if (count == 1){
printf("\nThere is a total of %i a", count);
}
}
printf("\nThere are a total of %i a's", count);
}
【问题讨论】:
标签: c if-statement printf cs50 conditional-operator