迭代直到遇到值的小数部分为 0

Iterate until encountering the value has the fractional part 0

我正在编写一个程序(为了练习和练习)计算数组中元素的数量,直到遇到小数部分为 0 的值 ,而不使用任何整数计数器变量。

我在下面使用整数计数器('i',顺便说一句)完成了它,但是如果不在循环中使用 'i',我无法找到一种方法。没有整数计数器怎么办?

输入:

5
1.2
-3.4
5.00
4
5.45

输出: 第一个整数前:2个元素

void int_or_float(float arr[], int n){
    int i, j;
    int counter = 0;
    char str[10];
    for (i = 0; i < n; i++){
        printf("%f\n", arr[i]);
        sprintf(str, "%f", arr[i]);
        for (j = 0; j < 9; j++){
            printf("%c\n", str[j]);
            if (str[j] == '.' && str[j + 1] == '0'){
                printf("Aborted!");
                printf("\n\nBefore the first integer: %d elements", i);
                j = 11;
                i = n + 1;
            }
        }
    }
}

int main(){
    int n, i;
    float *things;
    scanf("%d", &n);
    things = malloc (n * sizeof(float));
    for (i = 0; i < n; i++){
        scanf("%f", &things[i]);
    }
    printf("\n");
    int_or_float(things, n);
    return 0;
}

你不能用这个吗?

for(i=0; i<n; i++)
{
    if(round(arr[i])==arr[i])
    {
        printf("Before the first integer: %d elements\n",  i);
        return;
    }
}

我真的不明白这样做有什么意义,但是如果没有 i:

void int_or_float(const float *arr, int n){
    int j;
    float counter = 0.0f;
    char str[10];
    while(n-- >0){
        printf("%f\n", *arr);
        sprintf(str, "%f", *arr++);
        for (j = 0; j < 9; j++){
            printf("%c\n", str[j]);
            if (str[j] == '.' && str[j + 1] == '0'){
                printf("Aborted!");
                printf("\n\nBefore the first integer: %f elements\n", counter);
                j = 11;
                n=0;
            }
        }
        counter = counter+1.0f;
    }
}

OP 确实需要一个解决方案而不使用任何整数计数器变量。不使用计数器怎么能数数呢?通过使用指针在数组中前进,但这只有在你包含一个哨兵时才有效,这样你就可以终止了。假设这个哨兵是一些负数。

main()) 中,你需要一个额外的哨兵元素。

int_or_float() 中,您可以使用指针遍历数组。

#include <stdio.h>
#include <stdlib.h>

void int_or_float(float arr[]) {    // removed int n
    float *ptr = arr;
    int ival;
    while (*ptr >= 0) {
        printf("%f\n", *ptr);
        ival = (int)*ptr;
        if (*ptr == (float)ival) {
            printf("Aborted!");
            printf("\n\nBefore the first integer: %d elements", ptr - arr);
            return;
            }
        ptr++;
        }
    printf("\n\nNo integer values found");
    }

int main() {
    int n, i;
    float *things;
    scanf("%d", &n);
    things = malloc ((n+1) * sizeof(float));  // extra for sentinel
    for (i = 0; i < n; i++){
        scanf("%f", &things[i]);
    }
    things[i] = -1;         // sentinel
    printf("\n");
    int_or_float(things);   // n removed
    free (things);          // remember to free memory
    return 0;
}

必须指出的是,并不是所有的整数都可以用浮点数来精确表示。

您还应该检查 malloc()scanf() 的 return 值。