新手上路,c语言中,for循环语句,循环变量除了整形是否可以用其他的如浮点或字符等等
他就3个语句,只有中间的最终结果判断0或非0,其他2个怎么搞都可以。
比如 for (float t = fun(x), fun2(y); t < 1e-5; t = fun3(t), x = fun4(y))
在C语言中,for循环语句的循环变量可以是整型、浮点型或字符型等。以下是一个简单的示例:
#include <stdio.h>
int main() {
// 使用整型循环变量
for (int i = 0; i < 10; i++) {
printf("%d
", i);
}
// 使用浮点型循环变量
for (float f = 0.0; f < 1.0; f += 0.1) {
printf("%.1f
", f);
}
// 使用字符型循环变量
for (char c = 'A'; c <= 'J'; c++) {
printf("%c
", c);
}
return 0;
}
完全可以,比如
#include <stdio.h>
int main()
{
for (char *s = "hello"; *s != '\0'; s++) putchar(*s);
return 0;
}
for (A;B;C) D;
//等价于
{
A;
while (1) {
if (!(B)) break;
D;
C;
}
}
【相关推荐】
区分大小写
#include <stdio.h>
#include <stdlib.h>
void main()
{
//声明接收字符串的数组
char str[26];
//声明统计次数的数组
int count[26] = {0};
int count1[26] = {0};
int i,j;
for(i = 0;i < 26;i++)
{
scanf("%c",&str[i]);
}
//for循环统计次数
for(i = 0;i < 26; i++)
{
int number = str[i] - 'a';
//统计字符出现的次数
count[number] += 1;
}
for(i = 0;i < 26;i++)
{
if (count[i] > 0)
{
printf("%c出现了%d次\n", 'a' + i, count[i]);
}
}
for(j = 0;j < 26; j++)
{
int number = 0;//前面用过,现在初始化为 0
number = str[j] - 'A';
//统计字符出现的次数
count1[number] += 1;
}
for(j = 0;j < 26;j++)
{
if (count1[j] > 0)
{
printf("%c出现了%d次\n", 'A' + j, count1[j]);
}
}
}
不区分大小写
#include <stdio.h>
#include <ctype.h>
int main()
{
int num[26]={0};
char ch='1';
int i;
while((ch=getwchar())!='\n'&&0>=(toupper(ch)-'A')<=26)//从键盘获取字符ch,判断字符 ch 是否字母
++num[toupper(ch) - 'A'];//是字母的话,数组num对应的下标元素加一
for(i=0;i<26 ;i++ )//输出,数组num 下标加'A' 就是对应字母,数组下标对应元素num[i]就是字母个数
printf("%c %d\n",i+'A',num[i]);
return 0;
}