这是我的想法:sizeof()是一个计算变量有多大的运算符.sizeof(variable type)可以计算某种类型的大小.数组中元素的数量由下式给出sizeof(<array name>) / sizeof(variable type).
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
double b[] = {1 , 2 , 3 , 4 , 5};
printf("How many elements the array contains : %d\n" , sizeof(b) / sizeof(double));
system("pause");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出为5是正确的.
我想知道是否有更有效的方法来计算它?比方说,一个C函数.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char qq[] = {'a' , 'b' , 'c' , 'd'};
char qqq[] = "abcd";
printf("%d\n" , sizeof qq / sizeof qq[0]); // line A
printf("%d\n" , strlen(qq)); // line B
printf("%d\n" , sizeof qqq / sizeof qqq[0]); // line C
printf("%d\n" , strlen(qqq)); // line D
system("pause");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
看看上面的代码.数组中qq有四个元素,数组中qqq有五个元素,最后一个元素是'\0'.所以我理解A行打印4和C行打印5.D线对我来说还可以.我理解在处理字符串时strlen(qqq)等于"sizeof qqq / sizeof qqq[0] - 1".但是B线打印 …
我认为a完全相同b.但跑步的结果证明我错了.我以错误的方式了解哪一部分?
这是代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char a[] = "abcdefg";
char b[] = {'a' , 'b' , 'c' , 'd' , 'e' , 'f' , 'g'};
printf("%s\n" , a);
printf("%s\n" , b);
system("pause");
return 0;
}
Run Code Online (Sandbox Code Playgroud) 目标:比较输入的两个整数并输入较小的整数.如果两个整数相等,则程序发出警告并启动新循环.
平台:Visual Studio 2012.
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int get_lesser(int a , int b);
int main(void)
{
int a , b;
printf("1: Enter two integers: ");
while(scanf("%d%d" , &a , &b) == 2)
{
printf("THe smaller of the two integers entered is %d.\n" , get_lesser(a , b));
printf("2: Enter two numbers: ");
}
system("pause");
return 0;
}
int get_lesser(int a , int b)
{
if(a == b)
printf("The two integers equal.\n");
else if(a > b)
return b; …Run Code Online (Sandbox Code Playgroud)