在 C 中打印 long long

问题描述 投票:0回答:1

我正在开发一个将字符串转换为整数的程序。 代码工作得很好,但我收到了我无法理解的警告。 我试图查找它,但没有找到任何有用的东西。

这里是简单的代码:

#include <stdio.h>

int main() {

    char x[8] = "ABCDWXYZ";
    long long sum=0;
    
    for(int i=0; i<8; i++) {
        sum = sum*100 + (long long) x[i];
    }
    printf("%lli", sum);
    
    return 0;
}

这是我得到的警告:

too many arguments for format [-Wformat-extra-args]  //Line 11
unknown conversion type character 'l' in format [-Wformat=]  //Line 11
c printf
1个回答
-1
投票

%lld
是为
long long int
%llu
是为
unsigned long long int

现在,你已经写了

%lli
,这里
i
可能无效(尽管取决于你的编译器)。因此,使用
%lld
删除警告。

此外,您不需要将

x[i]
显式类型转换为
long long
,因为它是
signed
而不是
unsigned
,并且您使用的是
char
signed
。因此,类型转换不会对整体产生任何影响。

你应该为

9
分配
x
字节,只为
'\0'
空终止字符。

#include <stdio.h>

int main(void) {

    char x[9] = "ABCDWXYZ"; // +1 for NULL character for termination of string
    long long sum = 0;
    
    for(size_t i = 0; i < sizeof(x); i++) {
        sum = sum * 100 + x[i];
    }
    printf("%lld\n", sum);
    
    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.