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

标签 c iteration

我正在编写一个程序(为了练习和练习)计算数组中元素的数量,直到遇到小数部分为 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;
}

最佳答案

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;
}

必须指出的是,并非所有整数都能用 float 精确表示。

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

关于c - 迭代直到遇到值的小数部分为 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27745676/

相关文章:

c - 横向连接

c - c 中的 getline() 更改我的数据并导致内存错误

c - 为什么编译器显示 "Call to function with no prototype"?

c - 使用指针的程序运行不正常

recursion - Lisp 分析原子列表和列表

javascript - 两个循环遍历日期

c - 正在使用原子指针访问类型为 sig_atomic_t 的变量

java - 如何从最后到第一个迭代ArrayList?

Python——我在 for 循环中改变字典的方式的差异

javascript - 返回数组和子节点